Elasticsearch 版本控制保证数据一致性

Elasticsearch 版本控制保证数据一致性

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
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值