在弹性搜索中更新嵌套对象

时间:2020-07-15 10:31:22

标签: elasticsearch nested

问题:我在使用脚本更新Elastic Search中的嵌套对象时遇到问题。 我想更新文档的某些部分,以便可以达到预期的效果。

下面是示例代码。

  1. 我有以下产品映射
  PUT products
    {
      "mappings": {
          "properties": {
            "category": {
              "type": "nested",
              "properties": {
                "category_code": {
                 "type":  "keyword"
                  },
                 "zaiko": {
                  "type": "integer"
                 },
                 "categories": {
                   "type": "object",
                   "properties": {
                     "category_cd": {
                       "type": "text"
                     },
                     "zaiko": {
                       "type": "integer"
                     }
                   }
                 }
                }
              }
            }
        }
    }
  1. 在上面的映射中插入数据,如下所示

    POST /products/_doc/1
     {
      "category": [{
        "category_code": "201",
        "ziko": 100,
        "categories": {
          "category_code": "20101",
          "zaiko": 50
        }
      }]
    }
    
    POST /products/_doc/2
    {
    "category": [{
     "category_code": "201",
     "ziko": 100,
     "categories": {
      "category_code": "20102",
      "zaiko": 60
    }
    }]}
    
  2. 我想更新嵌套类别对象(Zaiko字段)并为其使用以下脚本

    POST /products/_update_by_query
     {
       "script": {
       "lang": "painless",
       "source": """
        for (int i=0; i < ctx._source.category.length; i++) { 
         if(ctx._source.category[i].categories.category_code == "20101"){
           ctx._source.category[i].categories.zaiko = params.zaiko;
         }
       } 
       """,
       "params": {
         "zaiko": 10
       }
     },
     "query": {
      "nested": {
       "path": "category",
       "query": {
         "bool": {
           "must": [
             {
               "match": {
                 "category.categories.category_cd": "20101"
               }
             }
           ]
         }
       }
      }
     }
    }
    

为响应此查询嵌套类别,zaiko字段未更新。 谁能建议我,如何使用脚本在Elastic Search中更新嵌套对象?

1 个答案:

答案 0 :(得分:1)

我似乎微不足道,但是如何从中更改最后一个match

"category.categories.category_cd": "20101"

"category.categories.category_code": "20101"

cd-> code

相关问题