惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

雷峰网
雷峰网
T
The Blog of Author Tim Ferriss
Scott Helme
Scott Helme
P
Proofpoint News Feed
D
Docker
The Hacker News
The Hacker News
云风的 BLOG
云风的 BLOG
Vercel News
Vercel News
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Project Zero
Project Zero
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
GbyAI
GbyAI
Jina AI
Jina AI
P
Proofpoint News Feed
P
Privacy & Cybersecurity Law Blog
T
Threat Research - Cisco Blogs
C
CERT Recently Published Vulnerability Notes
博客园 - 叶小钗
U
Unit 42
博客园_首页
Apple Machine Learning Research
Apple Machine Learning Research
Latest news
Latest news
T
The Exploit Database - CXSecurity.com
博客园 - 三生石上(FineUI控件)
博客园 - 聂微东
T
Threatpost
V
Vulnerabilities – Threatpost
C
Cisco Blogs
Spread Privacy
Spread Privacy
Cisco Talos Blog
Cisco Talos Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
V
Visual Studio Blog
G
GRAHAM CLULEY
Microsoft Azure Blog
Microsoft Azure Blog
博客园 - Franky
G
Google Developers Blog
Know Your Adversary
Know Your Adversary
F
Fortinet All Blogs
H
Hackread – Cybersecurity News, Data Breaches, AI and More
NISL@THU
NISL@THU
N
Netflix TechBlog - Medium
Y
Y Combinator Blog
L
Lohrmann on Cybersecurity
C
CXSECURITY Database RSS Feed - CXSecurity.com
Recent Announcements
Recent Announcements
量子位
S
Schneier on Security
I
Intezer
酷 壳 – CoolShell
酷 壳 – CoolShell
D
Darknet – Hacking Tools, Hacker News & Cyber Security

jdhao's digital space

Conversion between base64 and OpenCV or PIL Image 腾讯云对象存储博客图床开启 CDN 加速(不需要购买额外域名) Search and Replace in Multiple Files in Vim/Neovim Change Table Column Width in LaTeX Image or Table Side by Side in LaTeX LaTeX 并排显示图像或表格 Firenvim: Neovim inside Your Browser Content inside HTML tags missing in Latest Hugo? Creating Markdown Front Matter with Ultisnips Labelme JSON 标注格式转 voc XML 格式 Nifty Nvim Techniques That Make My Life Easier -- Series 6 macOS 下如何为视频制作字幕 Running Command Asynchronously inside Neovim Resolving Merge Conflict after Git Stash Pop Pylint: command not found? A Hands-on Experience with Neovim's Built-in LSP Support How to Convert PDF to Images with Imagemagick 互联网上常用缩略语集锦 File Backup in Neovim Converting PDF Pages to Images with Poppler Nifty Nvim Techniques That Make My Life Easier -- Series 5 Neovim Configuration for System-wide Use How to sort a list of tuple or list in Python -- lambda or itemgetter? Building A Vim Statusline from Scratch 人类第一颗原子弹爆炸始末 Distributed Training in PyTorch with Horovod Learning Expect Programming Essential Knowledge about SSH Nifty LaTeX Techniques -- Series 1 更改 Adsense 邮寄地址,重新寄送 PIN Mintty Tips and Configurations Generating Table of Contents for Markdown with Tagbar Convert Python Script to Exe on Windows with Pyinstaller Ubuntu on Windows Missing after Windows Update 使用代理加速 Mac 终端下载速度 My Experience with Several Zsh Plugin Managers 深圳租房小记 How to Install zplug inside Docker Container Why don't settings inside bashrc or bash_profile take effect? Setting Up Locale in Linux 谷歌 Adsense 申请及在 Hugo 中的配置 How to Write Algorithm Pseudo Code in LaTeX Nifty Nvim Techniques That Make My Life Easier -- Series 4 A Few Grammar Questions in Writing How to Read and Write Images with Unicode Paths in OpenCV Creating A Professional Table in LaTeX with booktabs How to Create Proper Folding for Vim/Nvim Configuration Linux Tips and Tricks -- s1 JPEG Image Orientation and Exif How Do I Show the Current File Path In Neovim? JPEG Image Quality in PIL Difference between view, reshape, transpose and permute in PyTorch Convert PIL or OpenCV Image to Bytes without Saving to Disk Fast Movement and Navigation Inside Vim or Neovim Unintuitive Behaviour of Case Sensitivity in Python glob Binding Keys in Zsh 几把机械键盘试用体验 Nvim Autocompletion with Deoplete Converting Markdown to Beautiful PDF with Pandoc Exclusive and Inclusive Motion in Neovim/Vim Nifty Nvim Techniques Which Make My Life Easier -- Series 3 Why Doesn't Jedi Autocompletion Work for Some Methods Vim-like Editing inside Browser Markdown 生成 HTML 时汉字之间出现多余空格问题 小米 9 安装谷歌商店(Google Play Store)与相关配置 Create Mappings That Take A Count in Neovim Spell Checking in Nvim English Words Completion inside Neovim/Vim How to Use Python Inside Vim Script with Neovim Nifty Little Nvim Techniques to Make My Life Easier -- Series 2 Setting up Ultisnips for Neovim Mac 上罗技 M590 鼠标设置 Nifty Little Nvim Techniques to Make My Life Easier -- Series 1 A Complete Guide on Writing LaTeX with Vimtex in Neovim Manipulating Images with Alpha Channels in Pillow Sublime Text Regular Expression Cheat Sheet Cropping Rotated Rectangles from Image with OpenCV Boosting Your Productivity on Terminal with Zsh and Plugins 最新版 Rime 输入法使用 (2022 更新) Display Image with Pillow inside Ubuntu on Windows Faster Directory Navigation with z.lua Cmder Advanced Configurations Nvim-qt Settings on Windows 10 Tmux Plugin Install and Management How to Debug Python Code in Terminal Markdown Writing and Previewing in Neovim -- A Complete Guide Line Number Settings for More Efficient Movement in Neovim 两个大规模中文语料库介绍以及处理 Windows 系统下几款程序员不可不用的神器 我的 2018 阅读清单 A Complete Guide to Neovim Configuration for Python Development How Is Newline Handled in Python and Various Editors? Two Issues Related to ImageFont Module in PIL 在 Listary 中调用 GoldenDict 或欧路词典查单词 Reading and Writing Text Files on Windows The Mathematics behind Font Shapes --- Bézier Curves and More 快速识别图片字体:字体识别工具介绍 Deoplete Failed to Load at Startup after Updating Python neovim Package What Is The Difference between pip, pip3 and pip3.6 Shipped with Anaconda3? Windows 10 系统下 Neovim 安装与配置
Elasticsearch Version Conflict Error
2024-09-12 · via jdhao's digital space

The version conflict error is often seen when doing document indexing operations in Elasticsearch.

Each document in Elasticsearch has two fields _seq_no and _primary_term records the state for this document. When we do concurrent changes to a document, each change has its own _seq_no and _primary_term. Elasticsearch will compare the _seq_no and _primary_term to avoid older changes overwrite the changes of newer changes.

When you update a document, you can specify sequence number and primary term, to make sure that there are no other changes made between when you get the sequence number/primary term and when you make your change. If the sequence number and primary term you specify does not match the one in the document, you will get 409 conflict error.

First, index document to my_index:

PUT my_index/_doc/123
{
"title": "monday"
}

This is the result you get.

{
  "_index": "my_index",
  "_id": "123",
  "_version": 1,
  "result": "created",
  "_shards": {
    "total": 2,
    "successful": 1,
    "failed": 0
  },
  "_seq_no": 0,
  "_primary_term": 1
}

If you check what is in document 123:

Result is:

{
  "_index": "my_index",
  "_id": "123",
  "_version": 1,
  "_seq_no": 0,
  "_primary_term": 1,
  "found": true,
  "_source": {
    "title": "monday"
  }
}

If you do another update to the document 123:

PUT my_index/_doc/123
{
  "title": "monday",
  "content": "this is monday"
}

You see something like this:

{
  "_index": "my_index",
  "_id": "123",
  "_version": 2,
  "result": "updated",
  "_shards": {
    "total": 2,
    "successful": 1,
    "failed": 0
  },
  "_seq_no": 1,
  "_primary_term": 1
}

The sequence number/primary term for document 123 will be changed (GET my_index/_doc/123):

{
  "_index": "my_index",
  "_id": "123",
  "_version": 2,
  "_seq_no": 1,
  "_primary_term": 1,
  "found": true,
  "_source": {
    "title": "monday",
    "content": "this is monday"
  }
}

In the document index API, we can also specify if_seq_no and if_primary_term parameter:

PUT my_index/_doc/123?if_seq_no=2&if_primary_term=1
{
  "title": "monday"
}

Since the sequence number and primary term does not match the document exactly, we see error:

{
  "error": {
    "root_cause": [
      {
        "type": "version_conflict_engine_exception",
        "reason": "[123]: version conflict, required seqNo [2], primary term [1]. current document has seqNo [1] and primary term [1]",
        "index_uuid": "n_LbDCbbT4O5mwgGWLOOKA",
        "shard": "0",
        "index": "my_index"
      }
    ],
    "type": "version_conflict_engine_exception",
    "reason": "[123]: version conflict, required seqNo [2], primary term [1]. current document has seqNo [1] and primary term [1]",
    "index_uuid": "n_LbDCbbT4O5mwgGWLOOKA",
    "shard": "0",
    "index": "my_index"
  },
  "status": 409
}

For document Delete API, we can also specify if_seq_no and if_primary_term:

DELETE my_index/_doc/123?if_seq_no=2&if_primary_term=1

Document 123 is there, but the sequence number and primary term does not match, you see errors:

{
  "error": {
    "root_cause": [
      {
        "type": "version_conflict_engine_exception",
        "reason": "[123]: version conflict, required seqNo [2], primary term [1]. current document has seqNo [1] and primary term [1]",
        "index_uuid": "n_LbDCbbT4O5mwgGWLOOKA",
        "shard": "0",
        "index": "my_index"
      }
    ],
    "type": "version_conflict_engine_exception",
    "reason": "[123]: version conflict, required seqNo [2], primary term [1]. current document has seqNo [1] and primary term [1]",
    "index_uuid": "n_LbDCbbT4O5mwgGWLOOKA",
    "shard": "0",
    "index": "my_index"
  },
  "status": 409
}

If the document does not exist (for example, if you do DELETE my_index/_doc/183244?if_primary_term=1&if_seq_no=1), you see error like this:

{
  "error": {
    "root_cause": [
      {
        "type": "version_conflict_engine_exception",
        "reason": "[183244]: version conflict, required seqNo [1], primary term [1]. but no document was found",
        "index_uuid": "n_LbDCbbT4O5mwgGWLOOKA",
        "shard": "0",
        "index": "my_index"
      }
    ],
    "type": "version_conflict_engine_exception",
    "reason": "[183244]: version conflict, required seqNo [1], primary term [1]. but no document was found",
    "index_uuid": "n_LbDCbbT4O5mwgGWLOOKA",
    "shard": "0",
    "index": "my_index"
  },
  "status": 409
}

This conflict error can also happen when you use delete_by_query API.

sequence number and primary term#

Sequence number represent the operation number that is performed on a document. Primary term means how many times that the primary shard for the index has been changed. If you create a new index and index a document, you see that the primary term is 1.

The primary term is introduced to solve doc version problems in a distributed system as Elasticsearch. You can find more about the motivation in this official blog1.

Elasticsearch delete versioning#

If you have a delete operation that targets at version 1000 of a document, but later you have an index operation that targets version 999 of the same document, if the delete operation is immediately and ES does not keep the version of the document, then the new index operation will succeed. However, the index operation targets an old version of the document, so it shouldn’t succeed. The document should still be deleted, not indexed again.

The index.gc_deletes setting is used to solve the above issue. It specifies how long the version number of deleted document is kept. By default, it is kept for 60 seconds.

ref:

version conflict when using delete by query#

When we use delete_by_query to delete a document, we will see potentially the ConflictError exception.

typical error#

The typical error message you see like this in the reason:

version conflict, required seqNo [0], primary term [1]. current document has seqNo [1] and primary term [1]

This means that you are getting an older version of the document. This can happen, for example, if you have a document in the index, then you index a new version of the docment, then immediately run the delete_by_query to delete the document. Below is a simple snippet to reproduce the error:

from elasticsearch import Elasticsearch

es_client = Elasticsearch(...)

index_name = "demo_index"
_id = "123456"
doc_old = {"title": "old title"}
doc_new = {"title": "new title"}

if es_client.indices.exists(index=index_name):
    es_client.indices.delete(index=index_name)

es_client.index(index=index_name, document=doc_old, id=_id)
es_client.indices.refresh(index=index_name)

search_response = es_client.search(index=index_name, seq_no_primary_term=True)
print(f"first search response: {search_response}")

# index updated doc
es_client.index(index=index_name, document=doc_new, id=_id)

# this refresh below is very important
# es_client.indices.refresh(index=index_name)

second_response = es_client.search(index=index_name, seq_no_primary_term=True)
print(f"second search response: {second_response}")

deletion_result = es_client.delete_by_query(
    index=index_name, query={"bool": {"should": [{"term": {"_id": _id}}]}}
)
print(f"deletion result: {deletion_result}")

but why? This is because after the second index operation using doc_new, the updated doc version is not immediately for search. You have to wait for Elasticsearch to refresh the index to make the new document searchable, which happens every 1 second by default and is controlled by setting index.refresh_interval. Or you can use the refresh api to refresh the index.

Under the hood, the API delete_by_query() search for the matching document and then delete them. However, the document version it gets is an older version. Actually if we compare the first response and second response, they are the same:

first search response: [{'_index': 'demo_index', '_id': '123456', '_seq_no': 0, '_primary_term': 1, '_score': 1.0, '_source': {'title': 'old title'}}]
second search response: [{'_index': 'demo_index', '_id': '123456', '_seq_no': 0, '_primary_term': 1, '_score': 1.0, '_source': {'title': 'old title'}}]

If you uncomment the es_client.indices.refresh() call in the above snippet, the delete_by_query call should run without issues.

another error#

Another conflict error I see is somewhat different, which has the following error reason:

version conflict, required seqNo [0], primary term [1]. but no document was found

This can happen, for example, when you use delete_by_query to delete a document from index. Then immediately you try to run delete_by_query again to delete the same document. Try the below code snippet:

from elasticsearch import Elasticsearch

es_client = Elasticsearch(...)
index_name = "demo_index"
_id = "123456"
doc_old = {"title": "old title"}

if es_client.indices.exists(index=index_name):
    es_client.indices.delete(index=index_name)

es_client.index(index=index_name, document=doc_old, id=_id)
es_client.indices.refresh(index=index_name)

search_response = es_client.search(index=index_name, seq_no_primary_term=True)
print(f"first search response: {search_response['hits']['hits']}")

deletion_result = es_client.delete_by_query(
    index=index_name, query={"bool": {"should": [{"term": {"_id": _id}}]}}
)
print(f"deletion result: {deletion_result}")

second_response = es_client.search(index=index_name, seq_no_primary_term=True)
print(f"second search response: {second_response['hits']['hits']}")

# es_client.indices.refresh(index=index_name)
deletion_result = es_client.delete_by_query(
    index=index_name, query={"bool": {"should": [{"term": {"_id": _id}}]}}
)
print(f"deletion result: {deletion_result}")

Remember the section on delete versioning. Actually after the you call the first delete_by_query, the document deletion is not yet fully done. The second search in the snippet can still show the document! So your second call to delete_by_query() gets an older version of the document and tries to delete it, but actually the document is not there anymore (searchable, but actually not there).

If we uncomment the es_client.indices.refresh() line, then the second call to delete_by_query() will not run into errors.

ref: