版本控制
Elasticsearch采用了乐观锁来保证数据的一致性,即当用户对document(文档,即关系数据库中表里的一条数据)进行操作时,并不需要对该document做加锁、解锁的操作,只需要指定要操作的版本即可。当版本号一致时,Elasticsearch会允许该操作顺利进行,而当版本号存在冲突时,Elasticsearch会提示冲突并抛出异常(VersionConflictEngineException)。
# 做更新操作时,指定对应的版本
PUT /lib/user/1?version=3
{
"frist_name": "Jane",
"last_name": "Smith",
"age": 32,
"about": "I like to collect rock albums",
"interests": ["music"]
}
# 由于指定的版本不存在,将会报错
{
"error":{
"root_case":[
{
"type": "version_conflict_engine_exception",
"reason": "[user][4]: version conflict,current version [2] is different than the one provided [3]",
"index_uuid": "ICnRur_NTn2s9sM04XE_rQ",
"shard": "0",
"index": "lib"
}
],
"type": "version_conflict_engine_exception",
"reason": "[user][4]: version conflict,current version [2] is different than the one provided [3]",
"index_uuid": "ICnRur_NTn2s9sM04XE_rQ",
"shard": "0",
"index": "lib"
},
"status": 409
}
Elasticsearch的版本号的取值范围为1到2^63-1。
- 内部版本控制:使用的时_version。
- 外部版本控制:elasticsearch在处理外部版本号时会与内部版本号的处理有些不同。它不再是检查_version是否与请求中指定的数据相同,而是检查当前的_version是否比指定的数值小。如果请求成功,那么外部的版本号就会被存储到文档中的_version中。
为了保持_version与外部版本控制的数据一致,使用version_type=external
# 做更新操作时,指定对应的外部版本控制
PUT /lib/user/1?version=3&version_type=external
{
"frist_name": "Jane",
"last_name": "Smith",
"age": 32,
"about": "I like to collect rock albums",
"interests": ["music"]
}
# 由于指定version_type=external外部版本控制时,
# 设置version要大于当前文档的最大版本(例如当前版本是3,则设置的版本要大于3),
# 否则将会报错
{
"error":{
"root_case":[
{
"type": "version_conflict_engine_exception",
"reason": "[user][4]: version conflict,current version [2] is different than the one provided [3]",
"index_uuid": "ICnRur_NTn2s9sM04XE_rQ",
"shard": "0",
"index": "lib"
}
],
"type": "version_conflict_engine_exception",
"reason": "[user][4]: version conflict,current version [2] is different than the one provided [3]",
"index_uuid": "ICnRur_NTn2s9sM04XE_rQ",
"shard": "0",
"index": "lib"
},
"status": 409
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。