有很多关于Elasticsearch如何支持文档级外部版本控制的文档。但是,如果想要进行部分更新(例如,对特定字段),在字段级别进行此类型的版本检查会很有用。
例如,假设我有一个对象字段name
,其原始字段为value
和timestamp
。如果timestamp
值大于Elasticsearch中当前的值,我只希望部分更新成功。
有一种简单的方法吗?可以用脚本完成吗?或者有更标准的方法吗?
答案 0 :(得分:1)
是的,使用脚本很容易。见https://www.elastic.co/guide/en/elasticsearch/reference/2.0/docs-update.html。
我在这里写了一个例子来更新“value”字段,当且仅当指定的时间戳值(在参数update_time中给出)大于“timestamp”字段时。如果timestamp字段值小于update_time参数,那么它将被更新,否则将不会执行更新。
curl -XPOST 'localhost:9200/test/type1/1/_update' -d '{
"script" : {
"inline": "if(ctx._source.name.timestamp > update_time){ ctx.op = \"none\"};
ctx._source.name.value = value; ctx._source.name.timestamp = update_time;",
"params" : {
"update_time" : 432422,
"value": "My new value"
}
}
}'
如果需要,您可以在脚本中获取当前时间,而不是作为参数传递,例如:
update_time = DateTime.now().getMillis()