update是常用操作,官方地址:https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-update.html

直接通过id更新(_update)

最直接的就是通过id进行更新:

curl --cacert http_ca.crt -u elastic -XPOST https://localhost:9200/test_record/_update/qDK5HIQB8xpN1Xtdcm4P?pretty  -H 'Content-Type: application/json' -d '{"script":{"source":"ctx._source.counts--","lang":"painless"}}'

上面的命令会把id为qDK5HIQB8xpN1Xtdcm4P,字段为counts的值减1。

如果要同时修改多个id要怎么做呢?直接用{}即可。

https://localhost:9200/test_record/_update/{qDK5HIQB8xpN1Xtdcm4P,qTK5HIQB8xpN1Xtdm245}?pretty

如果正确返回下面的结果:

{
  "_index" : "test_record",
  "_id" : "vdoNN4QBHJgRqN7h6HeV",
  "_version" : 3,
  "result" : "updated",
  "_shards" : {
    "total" : 2,
    "successful" : 1,
    "failed" : 0
  },
  "_seq_no" : 31,
  "_primary_term" : 4
}
{
  "_index" : "test_record",
  "_id" : "qjK5HIQB8xpN1Xtdy25q",
  "_version" : 3,
  "result" : "updated",
  "_shards" : {
    "total" : 2,
    "successful" : 1,
    "failed" : 0
  },
  "_seq_no" : 32,
  "_primary_term" : 4
}

通过查询id更新(_update_by_query)

上面的id也可以通过查询进行更新操作:

curl --cacert http_ca.crt -u elastic -XPOST https://localhost:9200/test_record/_update_by_query?pretty  -H 'Content-Type: application/json' -d '{"query":{"terms":{"_id":["qDK5HIQB8xpN1Xtdcm4P","qTK5HIQB8xpN1Xtdm245"]}},"script":{"source":"ctx._source.counts--","lang":"painless"}}'

和上面的效果是一样的,不过从性能上来说上面是发送了2条update命令,更这里只发送了1条update命令。从返回结果也可以看出区别

{
  "took" : 240,
  "timed_out" : false,
  "total" : 2,
  "updated" : 2,
  "deleted" : 0,
  "batches" : 1,
  "version_conflicts" : 0,
  "noops" : 0,
  "retries" : {
    "bulk" : 0,
    "search" : 0
  },
  "throttled_millis" : 0,
  "requests_per_second" : -1.0,
  "throttled_until_millis" : 0,
  "failures" : [ ]
}

通过查询关键字更新(_update_by_query)

curl --cacert http_ca.crt -u elastic -XPOST https://localhost:9200/test_record/_update_by_query?pretty  -H 'Content-Type: application/json' -d'{"query":{"match":{"key":"中华人民共和国"}},"script":{"source":"ctx._source.counts--","lang":"painless"}}'

这条命令是把含关键字为中华人民共和国记录的counts都减1,如果正确就会返回下面的结果

{
  "took" : 184,
  "timed_out" : false,
  "total" : 5,
  "updated" : 5,
  "deleted" : 0,
  "batches" : 1,
  "version_conflicts" : 0,
  "noops" : 0,
  "retries" : {
    "bulk" : 0,
    "search" : 0
  },
  "throttled_millis" : 0,
  "requests_per_second" : -1.0,
  "throttled_until_millis" : 0,
  "failures" : [ ]
}
0

本文为原创文章,转载请注明出处,欢迎访问作者网站(和而不同)

发表评论

error: Content is protected !!