- 文档冲突
- 外部系统版本控制
并发运行时的数据控制. 悲观锁: 假设有冲突发送, 阻塞资源的访问, 只有一个线程对其修改 乐观锁: 不会阻塞正在尝试的操作, 使用版本号, 只有当前最新的版本号或者大于当前版本号才能修改成功, 程序可以自行决定如何解决冲突, 例如重试更新, 使用新的数据等.
版本号的实战 : 创建文档 : 创建一个shopping 的索引 put请求 http://127.0.0.1:9200/shopping1
创建文档 put请求 http://127.0.0.1:9200/shopping1/_create/1001
请求体 :
{
"title": "华为手机",
"category": "华为",
"images": "http://huawei.com",
"price": 1999.00
}
响应 :
{
"_index": "shopping1",
"_type": "_doc",
"_id": "1001",
"_version": 1,
"result": "created",
"_shards": {
"total": 2,
"successful": 1,
"failed": 0
},
"_seq_no": 1,
"_primary_term": 1
}
执行修改 post请求 http://127.0.0.1:9200/shopping1/_update/1001
请求体如下 :
{
"doc": {
"name": "华为1"
}
}
得到的响应:
{
"_index": "shopping1",
"_type": "_doc",
"_id": "1001",
"_version": 2,
"result": "updated",
"_shards": {
"total": 2,
"successful": 1,
"failed": 0
},
"_seq_no": 2,
"_primary_term": 1
}
加版本号的更新, 请求url如下 http://127.0.0.1:9200/shopping1/_update/1001?version=1
得到的响应如下
{
"error": {
"root_cause": [
{
"type": "action_request_validation_exception",
"reason": "Validation Failed: 1: internal versioning can not be used for optimistic concurrency control. Please use `if_seq_no` and `if_primary_term` instead;"
}
],
"type": "action_request_validation_exception",
"reason": "Validation Failed: 1: internal versioning can not be used for optimistic concurrency control. Please use `if_seq_no` and `if_primary_term` instead;"
},
"status": 400
}
最新的es不用version, 更换url http://127.0.0.1:9200/shopping1/_update/1001?if_seq_no=1&if_primary_term=0
得到的响应如下 :
{
"error": {
"root_cause": [
{
"type": "action_request_validation_exception",
"reason": "Validation Failed: 1: ifSeqNo is set, but primary term is [0];"
}
],
"type": "action_request_validation_exception",
"reason": "Validation Failed: 1: ifSeqNo is set, but primary term is [0];"
},
"status": 400
}
查询最新的数据的版本 : get请求 http://127.0.0.1:9200/shopping1/_doc/1001
响应如下 : seq为2 , term是1
因此使用如下的post请求去修改 http://127.0.0.1:9200/shopping1/_update/1001?if_seq_no=2&if_primary_term=1
响应如下
{
"_index": "shopping1",
"_type": "_doc",
"_id": "1001",
"_version": 2,
"result": "noop",
"_shards": {
"total": 0,
"successful": 0,
"failed": 0
},
"_seq_no": 2,
"_primary_term": 1
}
外部系统版本控制
es可以使用 version_type = external 的外部版本号的配置. 测试: 当前的数据信息如下 : 发送post请求. 指定版本为外部的版本信息.
http://127.0.0.1:9200/shopping1/_doc/1001?version=1&version_type=external
此时报错如下
{
"error": {
"root_cause": [
{
"type": "version_conflict_engine_exception",
"reason": "[1001]: version conflict, current version [3] is higher or equal to the one provided [1]",
"index_uuid": "ey7CVOhYRwKVFbImn2XNKg",
"shard": "0",
"index": "shopping1"
}
],
"type": "version_conflict_engine_exception",
"reason": "[1001]: version conflict, current version [3] is higher or equal to the one provided [1]",
"index_uuid": "ey7CVOhYRwKVFbImn2XNKg",
"shard": "0",
"index": "shopping1"
},
"status": 409
}
提示版本冲突, 当前版本是3 , 使用的版本是1 . 必须要比当前版本高才行.
发送post请求 http://127.0.0.1:9200/shopping1/_doc/1001?version=4&version_type=external
请求体:
{
"doc": {
"name": "华为22222"
}
}