简体   繁体   English

如何使用 elasticsearch _update_by_query 更新字符串字段?

[英]How to update a string field with elasticsearch _update_by_query?

I have an index already filled with many documents.我有一个索引已经充满了很多文件。
All of the documents in the index have a name string field.索引中的所有文档都有一个name字符串字段。
I want to query and update all of them which have name = A and set it to name = B .我想查询和更新所有name = A并将其设置为name = B的人。

For clarity, in SQL it would be something like:为清楚起见,在 SQL 中,它类似于:
UPDATE FROM table SET name = 'B' WHERE name = 'A';

With elasticsearch API, according to the docs: https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-update-by-query.html根据文档,使用 elasticsearch API: https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-update-by-query.html

I tried this query:我试过这个查询:

POST my_index/_update_by_query
{
  "script": {
    "inline": "ctx._source.name = 'B'",
    "lang": "painless"
  },
  "query": {
    "term": {
      "name" : "A"
    }
  }
}

However it just returns that nothing was modified.但是它只是返回没有任何修改。 I can still find document with name=A, so they were not edited.我仍然可以找到 name=A 的文档,所以它们没有被编辑。

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

Any idea why my _update_by_query doesn't do anything?知道为什么我的 _update_by_query 什么都不做吗?

Found it, my string field was an analysed field, so I must use a match query like this : 找到它,我的字符串字段是一个分析字段,所以我必须使用一个匹配查询,如下所示:

POST my_index/_update_by_query
{
  "script": {
    "inline": "ctx._source.name = 'B'",
    "lang": "painless"
  },
  "query": {
    "match": {
      "name" : "A"
    }
  }
}

You can use ctx._source.put function like shown below您可以使用 ctx._source.put function 如下所示

POST /my_index/_update_by_query
{
  "script": {
    "source": """
     ctx._source.put('name','B');    
     """,
     "lang": "painless"
  }
  ,
  "query": {
    "bool": {
      "must": [
      {
          "match": {
          "name" : "A"                
          }
      }
      ]
    }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM