An article has been withdrawn: how to remove it from search

Preserve a withdrawal decision in a search projection: a hidden document, external revisions, delayed events, and a separate refresh boundary.

A withdrawn article should leave the available search selection.

An editor withdraws an article, its search document is updated, and the card disappears. Some time later, a handler receives an old publication event. If it simply overwrites the document, the missing card returns with its old title. The editor performed the actions in the right order; message delivery followed a different order.

The latest visibility decision needs a retained record that survives old-event redelivery, even when nothing remains to display. A hidden document carrying a revision provides that record in this teaching module. Continue the same article_demo on Symfony 8.1 and PHP 8.4+ with a separate disposable Elasticsearch 9.4.3 node rather than a second Symfony application.

Withdrawal also receives a new revision

First, define the unit of ordering: a site, a stable article identifier, and a locale. For each such tuple, one authoritative source issues increasing positive integer revisions. Each value describes the new complete state of that language version: its visibility, title, and summary. An index name, slug, or message receipt time does not replace this identity.

In the example, the document journal:note-a:uk encounters the following events. The table shows processing order, rather than calendar dates:

Event Revision Expected action
Publication 1 Store a visible document
Withdrawal 2 Store a hidden document
Delayed publication 1 Reject the older write
The same number delivered again 2 Do not apply an equal revision
Deliberate republication 3 Accept the new visible state
Delayed withdrawal 2 Retain the newer publication

The rule allows future republication when the editor actually makes a new decision. It prevents an old event from replacing a newer state that has already been accepted. If independent processes can issue the same number with different content, the revision source needs to resolve that problem. Arrival order at the search service cannot determine which editorial decision is correct.

Why deleting a document does not preserve the decision forever

After an Elasticsearch DELETE, the deleted document's version remains available for a limited period controlled by index.gc_deletes. The Delete API explicitly describes this boundary. Deleting a document with an external version therefore does not create an unlimited record of withdrawal. An event can arrive later than the internal deletion marker survives.

In this model, withdrawal is recorded using an ordinary indexing operation. The document continues to exist and retains its key and newer revision, while receiving visible=false. Its title and summary are replaced with empty strings. The complete synthetic record looks like this:

{
  "article_id": "note-a",
  "site": "journal",
  "locale": "uk",
  "revision": 2,
  "visible": false,
  "title": "",
  "summary": ""
}

An application marker of this kind is often called a tombstone. Here, it is an ordinary document rather than Elasticsearch's internal deletion mechanism. The lab does not remove it on a timer. Its revision remains available for comparison while that document is retained in the corresponding index.

Empty text fields describe the current _source. They do not establish that old text has been physically erased from every segment, backup, log, or cache. A separate data removal task needs its own policy and verification. This article uses a narrower acceptance criterion: an older write must not restore a hidden search card after a newer revision has been accepted.

Strict version comparison happens at the write boundary

The adapter supplies the revision as version and sets version_type=external. Under the Index API rules, this write is accepted when the document does not exist or its current version is strictly lower. Elasticsearch performs the check internally. A preliminary GET, a comparison in PHP, and a subsequent unconditional PUT would leave a gap for another write.

An equal revision also produces a conflict. This helps with repeated delivery: the same number cannot overwrite the stored value. However, a 409 response alone does not prove that the payload was identical. A changed payload carrying the same number is rejected too. The example calls the outcome not_applied_version_conflict to preserve this distinction.

Using external_gte would change the rule and allow an equal number; the documentation warns that this mode requires care. This model needs strict increases. Intermediate numbers may be skipped because each event contains the complete state. Partial commands such as “add a tag” need an additional protocol before this model can be applied to them.

Before sending a request, the adapter checks required fields, types, supported locales, and whether text agrees with visibility. A revision represented as a string, fraction, or negative number is rejected. Arbitrary extra fields do not reach the index either. These checks protect the example's contract; a separate trusted channel must establish the event publisher's authenticity.

An accepted write still has to become searchable

After a successful write, the current document and search results can differ. The Get API supports realtime reads, while search sees changes after a refresh. Reading a hidden document with GET is therefore insufficient to claim that no search request can still return its old card.

To make this boundary observable, the lab disables periodic refresh with -1. After writing the withdrawal, it should read the new state through realtime GET and the old card through search. It then performs an explicit refresh, after which the repeated search should be empty. This is a controlled sequence that does not rely on waiting an arbitrary number of seconds.

The refresh parameter distinguishes an ordinary write, a forced refresh, and waiting for a refresh. In this lab, refresh=false does not trigger one, while wait_for with periodic refresh disabled could wait without completing. A real workload needs a separate decision about visibility delay and the cost of refreshes.

Until the event has been delivered and the refresh has occurred, the application needs a current availability check against the source of truth before displaying a card. Keep that protection separate from the projection mechanism. This new lab does not implement a primary database or a transaction between that database and Elasticsearch, so it does not establish immediate withdrawal throughout a product.

Check the locale and site when writing and reading

The document key includes its site and locale. Withdrawing the Ukrainian version must not alter the English version, and the same local identifier on another site belongs to another document. A read request also needs to restrict its scope. This is the example's complete query builder:

<?php

declare(strict_types=1);

namespace App\SearchWithdrawal;

final class PublicSearch
{
    public static function request(string $site, string $locale, string $query): array
    {
        PublicationEvent::assertScope($site, $locale);
        if (trim($query) === '' || strlen($query) > 256 || preg_match('//u', $query) !== 1) {
            throw new \InvalidArgumentException('A bounded UTF-8 search query is required.');
        }
        return [
            'size' => 20,
            'version' => true,
            'sort' => [['article_id' => 'asc']],
            'query' => ['bool' => [
                'filter' => [
                    ['term' => ['site' => $site]],
                    ['term' => ['locale' => $locale]],
                    ['term' => ['visible' => true]],
                ],
                'must' => [['multi_match' => ['query' => $query, 'fields' => ['title', 'summary']]]],
            ]],
        ];
    }
}

In a bool query, the filter conditions jointly restrict matches without contributing to relevance scores. Selecting visible=true is part of every public search in this example. It returns up to 20 cards in deterministic order for verification; the lab does not evaluate ranking quality or complete pagination.

If a product needs to withdraw the entire article, each available locale needs a new hidden state, or the product must use another explicitly defined aggregate model. A partly completed sequence is not an atomic withdrawal of every language. Likewise, a query filter does not replace Elasticsearch access permissions: a client that can read the index directly can see internal documents. Keep the index behind the application's access boundary.

Run the module in the same application

Add src/SearchWithdrawal, WithdrawalLabCommand, and fixtures/search-withdrawal/withdrawal-event.json. LocalElasticsearch and EvidenceDirectory from the previous exercise remain the shared owners of guard, transport, and evidence handling. Add only the command entry under the existing services block.

services:
    App\Command\WithdrawalLabCommand: ~

The separate Elasticsearch 9.4.3 run executed 17 scenario groups: visibility before/after refresh, withdrawal, delayed publication, equal revisions with identical and changed payloads, a first-arriving tombstone, site/locale boundaries, newer publication, and delayed withdrawal. Separate checks cover missing documents, invalid events, and origin/index guards.

These are real HTTP scenario groups rather than PHPUnit tests. They ran on PHP 8.5.12; a separate shared SearchLab test set checks the local guard and transport without replacing the search runtime.

The prerequisite is your own disposable local Elasticsearch 9.4.3 node rather than an existing cluster. Configure single-node mode, a random cluster nonce, a loopback-only HTTP port, no host data mounts, and disabled index auto-creation. This local experiment does not model security/TLS; the node is unsuitable for a shared or remote host.

Shared LocalElasticsearch accepts only the exact origin http://127.0.0.1:PORT, checks cluster.name/version, and validates the index nonce. Redirects are disabled; idle timeout is 5s, total duration is bounded at 15s, and streaming response reads are capped at 1 MiB. Operations require exact indices created by that object. Loopback and a nonce guard against an accidental foreign target without authenticating local users.

cluster.name is withdrawal-lab-<24 lowercase hex>, and the index is withdrawal_lab_<the same 24 hex>. The earlier projection node has a different identity; do not reuse it for this sequence.

SEARCH_WORKSPACE="$(mktemp -d)"
php bin/console app:withdrawal-lab "$SEARCH_WORKSPACE/withdrawal" \
  --url="$SEARCH_LAB_URL" --cluster="$SEARCH_LAB_CLUSTER" --index="$SEARCH_LAB_INDEX"

The URL and cluster identity in the command must come from your own disposable-node launcher. Never substitute another service. The command reserves a new absolute directory under a trusted canonical parent; existing files, directories, and symlinks are rejected. It writes report.json without overwriting; the primary store in exercise 065 now uses MySQL 8.4/InnoDB. This module does not connect to that store or implement its own SQL backend. Repeating the exercise needs another new directory.

Only the launcher owner removes its container after verifying its exact ID/label. The commands perform no global Docker cleanup, delete no foreign indices, and configure no production TLS or roles.

A rebuild also needs the record of withdrawal

A hidden document uses storage, but removing it solely because of its age is unsafe while old messages can still arrive. Cleanup needs a proven limit on replay or another retained revision boundary. Merely expecting the queue to be empty does not establish that limit.

A new index also needs to know the current hidden states. If a rebuild includes only visible articles and immediately admits old messages for empty keys, the protection against resurrection disappears with the previous revisions. The rebuild protocol, index generations, and catching up with changes remain separate work.

A useful acceptance criterion can be stated precisely: once withdrawal has been applied and the required refresh has completed, public search does not show that language version, and an older event cannot restore it. A deliberate new publication carrying a higher revision has its own permitted path. Verify these transitions together with the durability of the record of the latest decision.

  1. Data & Infrastructure Search as a projection: why Elasticsearch should not be the only article store
  2. Data & Infrastructure Rebuilding a search index without mixing old and new schemas
  3. Platform Engineering Old events arrive later: revisions and asynchronous change ordering