Elasticsearch Document 的 _version 元数据
文字内容整理自B站中华石杉的 Elasticsearch 顶尖高手系列课程核心知识篇
对于为什么需要并发控制,我觉的不需要解释(如果你想听,那么可以留言,我补一篇),和所有的数据库系统所面临的问题是一样的。乐观锁、悲观锁,这些也都是常见的概念。
悲观锁
优点:方便,直接加锁,对应用程序透明,不需要额外操作
缺点:并发能力很低,同一时间只能有一个线程操作数据
乐观锁
优点:并发能力很高,不给数据加锁,大量线程并发操作
缺点:麻烦?每次更新的时候,都要先比对版本号,然后可能需要重新加载数据,再次修改,然后再写;这个过程可能重复好几次。

_version元数据
PUT /test_index/test_type/6
{
"test_field": "test test"
}
# 201 success
{
"_index" : "test_index",
"_type" : "test_type",
"_id" : "6",
"_version" : 1,
"result" : "created",
"_shards" : {
"total" : 2,
"successful" : 2,
"failed" : 0
},
"_seq_no" : 5,
"_primary_term" : 1
}
Elasticsearch 第一次创建一个 document 的时候,它的_version内部版本号就是1;以后,每次对这个document执行修改或者删除操作,都会对这个_version版本号自动加1;哪怕是删除,也会对这条数据的版本号加1
DELETE test_index/test_type/6
# 200 success
{
"_index" : "test_index",
"_type" : "test_type",
"_id" : "6",
"_version" : 2,
"result" : "deleted",
"_shards" : {
"total" : 2,
"successful" : 2,
"failed" : 0
},
"_seq_no" : 6,
"_primary_term" : 1
}
GET test_index/test_type/6
{
"_index" : "test_index",
"_type" : "test_type",
"_id" : "6",
"found" : false
}
POST test_index/test_type/6
{
"test_field": "deleted 6"
}
{
"_index" : "test_index",
"_type" : "test_type",
"_id" : "6",
"_version" : 3,
"result" : "created",
"_shards" : {
"total" : 2,
"successful" : 2,
"failed" : 0
},
"_seq_no" : 9,
"_primary_term" : 1
}
们会发现,在删除一个 document 之后,可以从一个侧面证明,它不是立即物理删除掉的,因为它的一些版本号等信息还是保留着的。先删除一条 document,再重新创建这条 document,其实会在 delete version基础之上,再把 version号加 1