簡體   English   中英

ElasticSearch:更新數組中的嵌套文檔

[英]ElasticSearch: Updating nested document in array

鑒於文件

curl -XPUT 'localhost:9200/test/me/here' -d '{
  "top" : [
    { "searchkey" : "change"},
    { "searchkey" : "keep"}
  ]
}'

我需要一個更新查詢,它將向子文檔添加新字段,搜索searchkey等於change ,並將保持任何其他子文檔完好無損。 那么預期的結果是:

{
  "top" : [
    { "searchkey" : "change", "newfield" : "newvalue"},
    { "searchkey" : "keep"}
  ]
}

運行按索引選擇內部文檔的查詢有效,但我事先不知道內部順序,無論如何它非常脆弱:

curl -XPOST 'localhost:9200/test/me/here/_update' -d '{
    "script" : "ctx._source.top[0].newfield = v",
    "params" : {
      "v" : "newvalue"
    }
}'

有沒有辦法告訴 ES 將新字段添加到匹配某些條件的內部文檔中? 就像是:

curl -XPOST 'localhost:9200/test/me/here/_update' -d '{
    "script" : "ctx._source.top[ctx._source.top.searchkey == s].newfield = v",
    "params" : {
      "s" : "change",
      "v" : "newvalue"
    }
}'

或者,如果我消除數組並將文檔轉換為:

{
"change" : {},
"keep" : {}
}

您可以將更新與腳本一起使用。 見示例:

PUT test/data/3/
{
   "source": [
     {
       "name": "A",
       "count": 1
     },
     {
       "name": "B",
       "count": 2
     },
     {
       "name": "c",
       "count": 3
     }
   ]
}

GET test/data/3

POST test/data/3/_update
{
 "script": " for (int i = 0; i < source.size(); i++) {boolean f = false;for (int j = 0; j < ctx._source.source.size(); j++) {if (ctx._source.source[j].name == source[i].name) {ctx._source.source[j].count = source[i].count;f=true;break;}}\nif(!f){ctx._source.source.add(source[i]);}}",
 "params": {
   "source": [
     {
       "name": "A",
       "count": 10
     },
     {
       "name": "B",
       "count": 30
     },
     {
       "name": "D",
       "count": 50
     }
   ]
 }
}

GET test/data/3

我們可以使用update_by_query API 來獲取符合條件的文檔,然后滾動json 數組來更新數組內的對象。

POST test/data/_update_by_query
{
    "script": {
        "lang":"painless",
        "source":"""
            for(int i=0;i<ctx._source.top.length;i++){
                if(ctx._source.top[i].searchkey == params.match_value){
                    ctx._source.top[i].new_field = params.new_value;
                }
            }
        """,
        "params" : {
             "match_value" : "change",
             "new_value" : "new_value"
         }
    },
    "query" : {
        "match" : {
            "top.searchkey": "change"
        }
    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM