AI Hints
Home›Elasticsearch Tutorial›Versions, Bulk and Refresh
Elasticsearch · Lesson 16 of 120

Versions and Conflicts

Two writers at once.

⏱ 2 min read▶ Video at 14:19🎓 Free
Watch this lesson in the Elasticsearch courseWatch on YouTube ↗Full Elasticsearch course

Two staff members open the same product at once. Both change the stock, and both save. Without care, one change silently overwrites the other. This is called a lost update.

  • Two people edit
  • Both save
  • One change is lost

Every write gets a number

Each change gets a sequence number, and a primary term. We read them with the document. Run it. Sequence number zero, primary term one. Together, they say exactly which version we read.

Dev Tools Consoletext
GET products/_doc/1?filter_path=_seq_no,_primary_term,_source
Output
{
  "_seq_no": 0,
  "_primary_term": 1,
  "_source": {
    "name": "Basecamp 2-Person Tent",
    "price": 237.99,
    "stock": 5
  }
}
Also uses _setup.http
PUT products
{ "settings": { "number_of_replicas": 0 } }

PUT products/_doc/1?refresh=true
{ "name": "Basecamp 2-Person Tent", "price": 237.99, "stock": 5 }

Write only if unchanged

The first update says, only save if the document is still at sequence number zero. It works, and the number moves on to one. The second writer still thinks it's zero. Run it. The second write fails with a conflict, so nothing is lost.

Dev Tools Consoletext
PUT products/_doc/1?if_seq_no=0&if_primary_term=1&filter_path=result,_seq_no
{ "name": "Basecamp 2-Person Tent", "price": 237.99, "stock": 4 }

PUT products/_doc/1?if_seq_no=0&if_primary_term=1&filter_path=result
{ "name": "Basecamp 2-Person Tent", "price": 237.99, "stock": 3 }
Output
# PUT products/_doc/1 200 OK
{"result": "updated", "_seq_no": 1}

# PUT products/_doc/1 409 Conflict
{
  "error": {
    "type": "version_conflict_engine_exception",
    "reason": "[1]: version conflict, required seqNo [0], primary term [1]. current
    document has seqNo [1] and primary term [1]"
  },
  "status": 409
}
Also uses _setup.http
PUT products
{ "settings": { "number_of_replicas": 0 } }

PUT products/_doc/1?refresh=true
{ "name": "Basecamp 2-Person Tent", "price": 237.99, "stock": 5 }

Summary

Use if seq no and if primary term to save only if nobody else changed the document. A conflict tells you to read it again and retry. Next, writing many documents at once.

Key takeaways
  • _seq_no
  • if_seq_no
  • 409 conflict
Next up: The Bulk API — many writes, one request