使用update_by_query API更新多个文档?

时间:2017-03-06 09:00:38

标签: elasticsearch

使用update_by_query,我们只能更新映射中存在的现有字段,或者我们可以在所有文档中创建一个带有值的新字段。

因为我尝试了以下查询来在索引中的所有文档中创建新字段:

  {
  "query": {
    "filtered": {
      "filter": {
        "bool": {
          "must": [
            {
              "term": {
                "uniqueId": 805569568956
              }
            }
          ]
        }
      }
    }
  },
  "script": {
    "inline": "ctx._source.Univesity.Name.Region.Europe = 'UCLA'"
  }
}

IT会抛出这样的错误

     {
  "error": {
    "root_cause": [
      {
        "type": "script_exception",
        "reason": "failed to run inline script [ctx._source.Univesity.Name.Region.Europe = 'UCLA'] using lang [groovy]"
      }
    ],
    "type": "script_exception",
    "reason": "failed to run inline script [ctx._source.Univesity.Name.Region.Europe = 'UCLA'] using lang [groovy]",
    "caused_by": {
      "type": "null_pointer_exception",
      "reason": "Cannot get property 'Name' on null object"
    }
  },
  "status": 500
}

在elasticsearch.yaml中,我配置了以下属性:

script.inline: true
script.indexed: true
script.engine.groovy.inline.aggs:  on
script.engine.groovy.inline:          true

我的映射是这样的:

"mappings": {
         "Univesity": {
            "properties": {
               "Name": {
                  "properties": {
                     "Region": {
                        "properties": {
                           "Europe": {
                              "type": "string"
                           }
                           "Australia": {
                              "type": "string"
                           }
                        }
                     },

1 个答案:

答案 0 :(得分:0)

您需要使用引号,否则Elasticsearch引擎将查找名为UCLA的变量。您的内联脚本应该看起来像:

"script": {
    "inline": "ctx._source.University.collegename = 'UCLA'"
}

(注意加州大学洛杉矶分校的简单引用)

编辑:查看完整的查询示例:

POST employeeid/_update_by_query?conflicts=proceed
{
  "query":{
    "match": {
      "name": "Sam"
    }
  },
  "script":{
    "inline": "ctx._source.importance2 = 2000"
  }
}

另外要小心,因为doc提到这个更新的查询仍然是实验性的(参见:https://www.elastic.co/guide/en/elasticsearch/reference/master/docs-update-by-query.html):

  

逐个查询API是新的,应该仍然被认为是实验性的。

相关问题