Rebuilding a search index without mixing old and new schemas
One Symfony application and two Elasticsearch generations: external revisions, sample checks, alias cutover, and rollback after event replay.
A search document needs a new schema: readers must receive a different set of field names. Creating a new index and copying records is not enough. While the old generation serves requests, the source can change. Rolling back to the old index after a failed release can also bring back material that has already been withdrawn.
Continue one article_demo on Symfony 8.1 and PHP 8.4+: two index generations, an explicit replay boundary, and a validated return path. SearchRebuild uses a separate disposable Elasticsearch 9.4.3 node and the shared SearchLab guard without creating another Symfony application.
A new schema has its own name and reader
In the first generation, a document contains article_id, title, and summary. In the second, those fields are named content_id, headline, and excerpt. Content identity, site, locale, revision, and visibility retain their values. This small change makes the boundary between a stored format and the application's response format visible.
Each generation receives a separate index with a strict mapping. The new mapping is created before copying: the Reindex API does not automatically transfer the source's settings and mapping. Each schema also has its own marker in the index metadata in this laboratory.
The reader has two known adapters. Each builds a query for its schema and converts the response into a common card. Simply adding both indices to one search alias would not solve this: a request could mix documents with different formats or show two copies of the same article.
A journal boundary differs from a document revision
The teaching journal contains eight events. Each has a global sequential offset, while the complete state of a language version has its own revision. Its key combines site, stable ID, and locale. A revision answers which state of that document is newer; an offset shows how far a particular generation has progressed through the shared journal.
The first six events produce five current documents. They include Ukrainian and English versions of one note, another visible note, a withdrawn item, and a record from another site. There are more events than documents because publishing and withdrawing one key successively change the same state.
Before rebuilding, the source is frozen at boundary 6. The old index must apply the entire contiguous range through it. A marker saying “the last observed offset was 6” would be insufficient if event 5 were missing. In our sequential command, the checkpoint advances only after the write for each next event is accepted.
This checkpoint lives in one process's memory. It serves the teaching exercise's transition checks, but it is not a persisted crash recovery protocol. A reliable journal, transactional position storage, and multiple concurrent consumers require a separate design.
Hidden state moves into the new generation too
A withdrawn item remains a document with visible=false, empty text fields, and a newer revision. It remembers an accepted decision. Copying only visible cards would make the new index forget that revision, allowing a delayed publication to arrive at an empty key.
In the exercise, _reindex reads all five documents and a short script renames three fields. The destination uses version_type=external: copying should preserve the source's external versions. Subsequent writes also use strict revision comparisons; the Index API describes accepting only a higher version in this mode.
Hidden documents do not pass the public filter, but they take part in completeness checks. Transferring a tombstone does not physically erase old text from every segment, copy, or log. The goal here is specific: the new generation must remember the latest accepted visibility revision.
Equal counts do not imply equal data
After _reindex, the command must check for timeouts, failures, and version conflicts, as well as the expected copying counters. This small dataset should produce five created documents and no updates in the previously empty destination. An HTTP response alone does not replace those conditions.
Next, compare the total count and canonical samples through the appropriate adapters. The dataset is small enough for all five keys to serve as samples. For each one, compare the entire normalised record and external version, including the hidden note, English locale, and other site.
With a large dataset, a few well-chosen samples and matching counts provide only partial confidence. They can miss a changed title, a lost revision, or omissions offset by extra records. The extent of the evidence must match the extent of the check; a sample cannot be called a complete reconciliation.
A refresh is required before search checks. Periodic refresh is disabled in the laboratory, and an explicit update of search visibility follows a completed set of writes. Checking the new state by reading a document and checking its presence in search are separate steps.
The alias changes in one transition
The reader alias has exactly one target. Before switching, check its current target, the candidate's checkpoint, its count, and its samples. Then submit one action removing the old association and one adding the new association. The following shows the request shape; the laboratory itself uses random names for indices it owns:
{
"actions": [
{
"remove": {
"index": "catalog-v1",
"alias": "catalog-read",
"must_exist": true
}
},
{
"add": {
"index": "catalog-v2",
"alias": "catalog-read"
}
}
]
}
The Aliases API supports atomic changes to multiple associations but permits partial outcomes for some errors. must_exist=true prevents successfully adding a new target after failing to remove a missing association. The command also checks the overall response, individual action results, and the alias's actual single target again.
Alias atomicity does not switch every reader's code. Our reader first resolves a concrete target, selects its known adapter, and queries that index. An individual request therefore uses a consistent format and generation. A request already in progress may finish reading the old generation; the laboratory does not promise that all clients switch simultaneously.
Rollback requires a fresh eligibility check
After the first transition, the new index receives events 7 and 8. The first withdraws a note's Ukrainian version; the second changes another item's title. The old generation receives neither write.
| Stage | Source boundary | Old generation | New generation | Reads |
|---|---|---|---|---|
| Validated initial snapshot | 6 | Through 6 | Through 6 | Old |
| First switch | 6 | Through 6 | Through 6 | New |
| Two new decisions | 8 | Through 6 | Through 8 | New |
| Premature rollback attempt | 8 | Through 6 | Through 8 | Remain on new |
| Event replay and another check | 8 | Through 8 | Through 8 | Can return to old |
Both indices still contain five documents. However, the old generation shows the withdrawn card and the previous title. This is a deliberate counterexample to checking only counts. The command must reject rollback before changing the alias because checkpoint 6 does not match the current boundary of 8.
For an eligible return, freeze the source again. Events 7–8 are applied to the old schema through its writer, followed by refresh and another reconciliation. The samples now include two hidden language versions and a changed title. The English version and the other site's record retain their states. Only then may the same switching mechanism return the reader.
A separate scenario must send an old publication event after rollback. The expected outcome is an external version conflict, rather than the card returning. The restored old schema must retain current withdrawal history just as the new one does.
Failure does not make a candidate ready
The command stops dependent stages at the first unmet condition. An incomplete copy does not receive the reader alias. A switch is also rejected if the expected current target has changed. The laboratory must exercise a real must_exist rejection to check that the previous target is preserved.
For long operations, a transport timeout does not prove the server stopped copying; the reindex examples discuss this. Our small laboratory finishes with its own disposable container. A production workflow needs separate rules for checking the task, stopping it, and cleaning up remnants.
A boundary the laboratory can examine
The separate Elasticsearch 9.4.3 run executed 22 sequential real HTTP scenario groups: two schemas, hidden revisions, counts/samples, cutover, stale rollback refusal, replay6→8, and reading three scopes. The model has one writer, a fixed journal, and controlled source freezes. Its checkpoint is memory-only, without distributed CDC, crash recovery, or proven uninterrupted availability.
Add src/SearchRebuild, RebuildLabCommand, and fixtures/search-rebuild/events.json to the same application. SearchLab remains the sole owner of loopback transport, nonce/ownership guards, and the evidence directory. Narrow methods permit mapping/count, a fixed schema1→2 reindex, and a controlled read alias without an arbitrary HTTP-path bypass. createIndex rejects top-level aliases; only the owned-alias operation creates one.
services:
App\Command\RebuildLabCommand: ~
Use your own disposable local Elasticsearch 9.4.3 node with cluster.name projection_lab_<16 lowercase hex>. Configure single-node mode, a loopback-only HTTP port, no host data mounts, and disabled index auto-creation. The command operates only on its own nonce indices _old/_new and alias _read created by its object. It rejects foreign names and an existing alias. This establishes neither production TLS/roles nor local-user authentication.
Add new entries under the existing services block, preserving earlier services and routes. After wiring, explicitly clear the dev no-debug cache: this is the runtime variant used by the CLI check. From the same article_demo root, run the command at a new absolute directory:
php bin/console cache:clear --env=dev --no-debug
LAB_WORKSPACE="$(mktemp -d)"
php bin/console app:rebuild-lab "$LAB_WORKSPACE/run" --env=dev --no-debug \
--url="$SEARCH_LAB_URL" --cluster="$SEARCH_LAB_CLUSTER"
In a real product, checking content availability in the primary source remains necessary: a new search generation does not eliminate delayed event delivery or an old cached response. This exercise has a narrower, testable criterion: every switch must lead to a generation that already contains the agreed data snapshot, and returning to an older schema must not reverse editorial decisions.
The native ES experiment ran on PHP 8.5.12. Its 22 groups are separate from PHPUnit: shared SearchLab has 15 tests with 71 assertions, including the retained 9/44 from earlier exercises. Reads use a concrete generation after alias resolution, and stale rollback refusal was checked before alias mutation.