1. 文章总数：961
2. 浏览总数：11,488,242
3. 评论：3873
4. 分类目录：103 个
5. 注册用户数：5844
6. 最后更新：2018年10月17日

bigdata_ai

# Elasticsearch乐观锁并发控制(optimistic concurrency control)

Elasticsearch是一个分布式系统。当documents被创建、更新或者删除，其新版本会被复制到集群的其它节点。Elasticsearch既是异步的(asynchronous )也是同步的(concurrent)，其含义是复制请求都是并行发送的，但是到达目的地的顺序是无序的。Elasticsearch系统需要一种方法使得老版本的文档永远都无法覆盖新的版本。

每当文档被改变的时候，文档中的_version将会被增加（+1）。Elasticsearch使用_version确保所有的修改都会按照正确的顺序执行。如果文档旧的版本在新的版本之后到达，它会被简单的忽略。

PUT /website/blog/1/_create
{
"title": "My first blog entry",
"text":  "Just trying this out..."
}


GET /website/blog/1


{
"_index" :   "website",
"_type" :    "blog",
"_id" :      "1",
"_version" : 1,
"found" :    true,
"_source" :  {
"title": "My first blog entry",
"text":  "Just trying this out..."
}
}


PUT /website/blog/1?version=1
{
"title": "My first blog entry",
"text":  "Starting to get the hang of this..."
}


{
"_index":   "website",
"_type":    "blog",
"_id":      "1",
"_version": 2
"created":  false
}


{
"error": {
"root_cause": [
{
"type": "version_conflict_engine_exception",
"reason": "[blog][1]: version conflict, current [2], provided [1]",
"index": "website",
"shard": "3"
}
],
"type": "version_conflict_engine_exception",
"reason": "[blog][1]: version conflict, current [2], provided [1]",
"index": "website",
"shard": "3"
},
"status": 409
}


Elasticsearch对409响应码的解释是：

The request could not be completed due to a conflict with the current state of the resource. This code is
only allowed in situations where it is expected that the user might be able to resolve the conflict and
resubmit the request. The response body SHOULD include enough information for the user to recognize the
source of the conflict. Ideally, the response entity would include enough information for the user or user
agent to fix the problem; however, that might not be possible and is not required.

Conflicts are most likely to occur in response to a PUT request. For example, if versioning were being
used and the entity being PUT included changes to a resource which conflict with those made by an earlier
(third-party) request, the server might use the 409 response to indicate that it can't complete the request.
In this case, the response entity would likely contain a list of the differences between the two versions in
a format defined by the response Content-Type.

(1)个小伙伴在吐槽
1. very nice.更新的时候必须好用。给你糖吃跟哥哥走2016-11-21 18:00 回复