当并发更新时会有更新冲突,见下面的演示
#!/bin/bash#clear firstcurl -XDELETE 'localhost:9200/test-concurrent-update?pretty'curl -XPOST 'localhost:9200/test-concurrent-update/type/1?pretty' -d '{ "count": 0}'#并发执行for ((i=0; i<10; i++))docurl -XPOST 'localhost:9200/test-concurrent-update/type/1/_update?pretty' -d '{ "script" : "ctx._source.count += 1"}' &donewait#check resultecho "check final result"# why must have to sleep some time or cannot query any result ?sleep 1curl -XPOST 'localhost:9200/test-concurrent-update/type/_search?pretty' -d '{ "query":{"match_all": {}}}'
执行上述脚本
$ bash test_concurrent_update { "acknowledged" : true}{ "_index" : "test-concurrent-update", "_type" : "type", "_id" : "1", "_version" : 1, "created" : true}{ "_index" : "test-concurrent-update", "_type" : "type", "_id" : "1", "_version" : 2}{ "error" : "VersionConflictEngineException[[test-concurrent-update][2] [type][1]: version conflict, current [2], provided [1]]", "status" : 409}{ "error" : "VersionConflictEngineException[[test-concurrent-update][2] [type][1]: version conflict, current [2], provided [1]]", "status" : 409}{ "error" : "VersionConflictEngineException[[test-concurrent-update][2] [type][1]: version conflict, current [2], provided [1]]", "status" : 409}{ "error" : "VersionConflictEngineException[[test-concurrent-update][2] [type][1]: version conflict, current [3], provided [2]]", "status" : 409}{ "error" : "VersionConflictEngineException[[test-concurrent-update][2] [type][1]: version conflict, current [3], provided [2]]", "status" : 409}{ "_index" : "test-concurrent-update", "_type" : "type", "_id" : "1", "_version" : 3}{ "_index" : "test-concurrent-update", "_type" : "type", "_id" : "1", "_version" : 4}{ "error" : "VersionConflictEngineException[[test-concurrent-update][2] [type][1]: version conflict, current [4], provided [2]]", "status" : 409}{ "error" : "VersionConflictEngineException[[test-concurrent-update][2] [type][1]: version conflict, current [4], provided [3]]", "status" : 409}check final result{ "took" : 4, "timed_out" : false, "_shards" : { "total" : 5, "successful" : 5, "failed" : 0 }, "hits" : { "total" : 1, "max_score" : 1.0, "hits" : [ { "_index" : "test-concurrent-update", "_type" : "type", "_id" : "1", "_score" : 1.0, "_source":{"count":3} } ] }}
期待count最终为10,但实际为3.其他的更新操作均因冲突导致更新失败。