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

qyyhg6bp  于 2023-11-17  发布在  ElasticSearch
关注(0)|答案(3)|浏览(168)

我有一个索引已经充满了许多文件。
索引中的所有文档都有一个name字符串字段。
我想查询和更新所有具有name = A的文件,并将其设置为name = B
为了清楚起见,在SQL中,它应该是这样的:
UPDATE FROM table SET name = 'B' WHERE name = 'A';
使用elasticsearch API,根据文档:https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-update-by-query.html
我试过这个查询:

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

字符串
但是它只是返回没有修改任何东西。我仍然可以找到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": []
}


为什么my _update_by_query不做任何事情?

oyjwcjzk

oyjwcjzk1#

找到了,我的字符串字段是一个分析字段,所以我必须使用这样的匹配查询:

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

字符串

0sgqnhkj

0sgqnhkj2#

您可以使用ctx._source.put函数,如下所示

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

字符串

n3ipq98p

n3ipq98p3#

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

字符串

相关问题