Video in progress
How do you keep an Elasticsearch/OpenSearch index for product search in sync with the service's DB, and how do you do a full reindex?
The DB is the source of truth and the index is a copy derived from it. I pass changes to an indexing consumer through outbox or CDC events and use versions so an old record can't overwrite a newer one. A full reindex goes into a new index, then the alias is swapped in an instant.
📖 Answer
The most common mistake is writing to two places in code:
productRepo.save(p);
searchClient.index(p); // if this fails, the index goes stale and nobody knows
That is the same dual write. The index falls behind the DB, and search shows deleted products.
A reliable setup:
product DB --(outbox or Debezium)--> Kafka: product-changed --> search-indexer --> ES
The indexer:
- rewrites the whole document by the event's
productId(not a partial update), so ordering and duplicates matter less; - passes the version to ES: with the
externalversion type, ES rejects a write with an older version itself; - receives deletes as events too and deletes the document.
client.index(i -> i.index("products")
.id(p.id().toString())
.version(p.version())
.versionType(VersionType.External)
.document(ProductDoc.from(p)));
A full reindex (the mapping changed, the analyzer was updated, the index got corrupted):
- A new index
products_v8is created. - A backfill job reads all products from the DB with keyset pagination and writes them. New changes must not be lost in the meantime either: the indexer writes to both indexes, or you remember the offset where the backfill started and replay from that point afterward.
- The document counts and random samples are compared.
- The
productsalias is switched fromproducts_v7toproducts_v8with a single atomic request. The search code knows only the alias. - The old index is deleted after a few days, to leave a way back.
Monitoring: the difference in document counts between the DB and the index, and the indexer lag. A daily reconciliation job (comparing 1000 random products in the DB and ES) catches silent drift.
Sign up to mark studied questions and save your progress.