Sub topic 11
Reindexing and Changing the Schema Safely
This chapter assumes you know what an index mapping is (see "Designing the index and its mapping") and how data flows from the source of truth into the index (see "Keeping the index in sync with the source of truth"). It also assumes basic familiarity with REST APIs. The examples use Elasticsearch-style syntax. OpenSearch is nearly identical. Other engines have equivalent ideas under different names.
Why schema changes are hard in a search index
In a relational database, ALTER TABLE can add a column and the engine handles the existing rows. A search index is different. An inverted index is built from analyzed terms, and those terms are written when a document is indexed. If you change how a field is analyzed, the terms already on disk are still the old ones. They do not change on their own.
For that reason most engines restrict what you can change on an existing field:
- You can usually add a new field.
- You usually cannot change a field's type, for example from
texttokeyword. - You cannot change the analyzer of a field that already holds data and expect old documents to follow.
- You cannot change the number of primary shards after the index is created (Elasticsearch offers split and shrink operations, but they have constraints of their own).
The standard answer is to build a new index with the new settings, copy the data into it, and then switch traffic. This is called reindexing.
When you need to reindex
| Change | Reindex needed? | Notes |
|---|---|---|
| Add a new field | Usually no | Old documents simply lack the field until they are updated. |
| Change a field type (`text` to `keyword`) | Yes | The stored structures differ. |
| Change an analyzer or add a token filter | Yes | Old terms were produced by the old analysis chain. |
| Change the number of primary shards | Yes, or split/shrink | Documents are routed by shard count. |
| Add a sub-field (multi-field) to an existing field | Partly | New sub-field is empty for old documents until they are re-indexed or updated in place. |
| Change replica count | No | A dynamic setting. |
| Engine major version upgrade | Sometimes | Indexes created two or more major versions back may not be readable. |
A useful rule: if the change alters what terms get written, or how documents are placed, old data must be rewritten.
The alias pattern
Applications should never query a physical index name such as products_v1. They query an alias, which is a named pointer to one or more indexes. Swapping the pointer is the step that makes a reindex invisible to users.
Set this up from the start:
PUT /products_v1
{
"mappings": {
"properties": {
"name": { "type": "text" },
"category": { "type": "keyword" }
}
}
}POST /_aliases
{
"actions": [
{ "add": { "index": "products_v1", "alias": "products" } }
]
}Your search code uses products. Your writers can use a separate write alias, or the same one, depending on how you handle the cutover (discussed below).
The alias switch is atomic. Both actions in one _aliases call are applied together, so no query ever sees zero indexes or two copies of the data.
POST /_aliases
{
"actions": [
{ "remove": { "index": "products_v1", "alias": "products" } },
{ "add": { "index": "products_v2", "alias": "products" } }
]
}The zero-downtime reindex workflow
Step 1: Create the new index
Create products_v2 with the new mapping, explicitly. Do not rely on dynamic mapping for the new index, since it would guess types from the first documents it sees.
Step 2: Backfill
There are two common sources for the backfill.
- The old index. Elasticsearch's
_reindexAPI copies documents from one index to another, optionally with a script to transform them. It is fast and needs no load on your primary database. The limit is that it copies_source. If the new mapping needs data that was never in the old documents, you cannot create it this way. Also, if_sourcewas disabled, this approach is unavailable. - The source of truth. A job reads rows from the primary database and indexes them. This is slower and adds database load, but it works for any change, and it also repairs any drift that built up in the old index.
POST /_reindex?wait_for_completion=false
{
"source": { "index": "products_v1", "size": 1000 },
"dest": { "index": "products_v2", "version_type": "external" }
}The call returns a task ID. Poll GET /_tasks/<task_id> to follow progress. Running a long reindex in the foreground ties up a client connection and breaks on timeouts.
With version_type: external in the destination, the copy only writes a document if its version is newer than what the destination already holds. This matters for the next step.
Step 3: Handle writes that arrive during the backfill
A backfill takes time, often hours. While it runs, users keep changing products. If you ignore those changes, the new index will be stale at cutover. There are two approaches.
Dual-write. The sync pipeline writes each change to both products_v1 and products_v2. The backfill and the live writes race, and external versioning settles the race. A document written by the live pipeline at version 9 will not be overwritten by the backfill's copy at version 7. This is the same idempotent pattern described in the data sync chapter:
PUT /products_v2/_doc/42?version_type=external&version=7
{
"name": "Trail running shoes",
"category": "footwear",
"price": 89.0,
"in_stock": true
}If the write returns a version conflict, that is the expected, harmless outcome: the index already has something newer.
Replay from a log. If your pipeline reads from a change stream or message queue with retention, note the position when the backfill starts. After the backfill finishes, start a consumer for products_v2 at that position and let it catch up. This avoids changing the live write path, but it needs a log with enough retention to cover the whole backfill.
Step 4: Verify
Before switching, compare the two indexes:
- Document counts:
GET /products_v1/_countandGET /products_v2/_count. Small differences are normal if writes are in flight. Large differences mean something failed. - Failures reported by the reindex task. Check the
failuresarray in the task result. A reindex can finish "successfully" with some documents rejected by the new mapping. - A fixed set of representative queries, run against both indexes, with the results compared. This is where relevance regressions show up. Your relevance evaluation set (see "Measuring and tuning relevance") is ideal here.
Step 5: Switch the alias
Use the atomic two-action _aliases call shown earlier. Queries after that moment hit products_v2.
Step 6: Keep a rollback window
Do not delete products_v1 immediately. Keep it, and keep dual-writing to it, for a period such as a day or a week. If the new index has a problem, switching the alias back is a single call. After that, stop writing to v1 and delete it.
The cost is storage and write load for the duration. That is usually cheap compared to an incident without a fast rollback.
Edge cases and common errors
- Mapping explosion in the new index. If you leave dynamic mapping on and the documents contain arbitrary keys, field counts can grow past limits. Set
"dynamic": "strict"or"false"on the new mapping when you control the schema. - Deleted documents reappearing. A deletion in the source of truth that happens during the backfill can be missed if the backfill reads a snapshot taken before the delete and the delete event was not dual-written. Include deletes in the dual-write or replay path. With external versioning, deletes also need a version, and a delete with a lower version than the current document is rejected.
- Backfill overload. A reindex competes with live queries for CPU and disk. Throttle it with
requests_per_second, and useslicesto parallelize only when the cluster has headroom.
POST /_reindex?wait_for_completion=false&requests_per_second=500&slices=auto
{
"source": { "index": "products_v1" },
"dest": { "index": "products_v2", "version_type": "external" }
}- Refresh interval. During a bulk backfill, set
refresh_intervalto-1and replicas to0on the new index to speed up indexing. Restore both before the cutover, or the new index will not return fresh results and will have no redundancy. - Transform bugs. If a script in
_reindexmutates fields incorrectly, every document is wrong. Test on a small sample with"max_docs": 1000first. - Application code coupling. If the new mapping renames a field, the query code must change too. Deploy query code that works with both mappings before switching the alias, or switch the alias and code together behind a feature flag.
Changes that avoid a full reindex
Not every change needs the heavy process.
- Add a field. Update the mapping with
PUT /products_v1/_mapping. Fill it for old documents with_update_by_queryif needed. - Add a multi-field. To make an existing
textfield also searchable askeyword, add a sub-field, then run_update_by_queryso existing documents populate it:
PUT /products_v1/_mapping
{
"properties": {
"name": {
"type": "text",
"fields": {
"raw": { "type": "keyword" }
}
}
}
}POST /products_v1/_update_by_query?conflicts=proceed&wait_for_completion=false- Search-time analyzers. A
search_analyzercan often be changed without reindexing, because it only affects the query side. Index-time analysis cannot.
Take care with _update_by_query: it rewrites every matched document, so it has the same load profile as a reindex, only in place and without an easy rollback. For risky changes, the new-index approach remains safer.
Planning for change from day one
- Name indexes with a version suffix and always query through aliases.
- Keep
_sourceenabled, so_reindexstays available. - Make the sync pipeline able to rebuild the whole index from the source of truth. If you can only update incrementally, you cannot recover from a bad mapping or lost index.
- Store an index schema version in your deployment configuration, so you know which mapping a given environment runs.
- Rehearse the reindex in a staging environment with realistic data volume, and record how long it takes. The duration tells you how long dual-writing must run and how large the rollback window storage cost is.
Exercise
Your team wants to change the name field from the standard analyzer to one that adds stemming. The index products_v1 has 40 million documents, and users keep updating products during the work. List the steps to deploy this change with no downtime, and explain how you stop the backfill from overwriting newer live updates.
Show answer
Create products_v2 with the stemming analyzer in its mapping. Start dual-writing live changes to both indexes. Run a throttled _reindex from products_v1 (or from the source database) into products_v2 with version_type: external, as a background task. Because every document carries the version from the source database, a backfill write with an older version is rejected with a version conflict, so it cannot overwrite a newer live update. Verify document counts, check the task for failures, and compare results of a fixed set of reference queries. Restore refresh_interval and replicas on products_v2, then switch the products alias from v1 to v2 in one atomic _aliases call. Keep v1 and its dual-write for a rollback window, then delete it.
Exercise
A teammate proposes adding a keyword sub-field name.raw to the existing name field on a live index and says no reindex is needed. Is that correct? What step is still required, and what risk does it carry?
Show answer
Adding the sub-field to the mapping is allowed without a new index, but it is empty for existing documents. You must run _update_by_query (or let documents be re-indexed by normal updates) so the sub-field gets populated. The risk is that _update_by_query rewrites every document in place, so it adds load comparable to a reindex and offers no quick rollback, unlike switching an alias back to the old index.