【问题标题】:remove objects from array that satisfying the condition in elastic search with javascript api使用javascript api从满足弹性搜索条件的数组中删除对象
【发布时间】:2014-10-07 09:24:07
【问题描述】:

假设我的弹性搜索文档中有一个数组类型字段,如下所示:-

"prog_lists": [
 {
  "description": "engineer",
  "age": 25,
  "name": "ashu"
 },
 {
  "description": "programmer",
  "age": 26,
  "name": "rajit"
 },
 {
  "description": "designer",
  "age": 27,
  "name": "naveen"
 }
]

我想删除名称等于 ashu 的对象,或者删除多个满足查询的对象,例如年龄大于 25 岁的对象

我可以通过指定对象中的所有内容来做到这一点,如下所示:-

client.update({
        "index": "daffo_netgear",
        "type": "array",
        "id": "2201",
        "body": {
            "script":"ctx._source.prog_lists.remove(list)",
            "params" : {
                    "list" :{
                        "description": "engineer",
                        "age": 25,
                        "name": "ashu"
                     }
             }
        }})

但我想这样做只是指定姓名或年龄

client.update({
        "index": "daffo_netgear",
        "type": "array",
        "id": "2201",
        "body": {
            "script":"ctx._source.prog_lists.remove(list)",
            "params" : {
                    "list" :{
                          "name": "ashu"
                     }
             }
        }})

我的node模块elasticsearch版本是2.4.2 elasticsearch server是1.3.2。

【问题讨论】:

    标签: node.js elasticsearch


    【解决方案1】:

    我得到了我的答案,它的解决方案是

    POST /twitter/twit/1/_update
    
    {
      "script": "item_to_remove = nil; foreach (item : ctx._source.list) { if (item['tweet_id'] == tweet_id) { item_to_remove=item; } } if (item_to_remove != nil) ctx._source.list.remove(item_to_remove);",
      "params": {"tweet_id": "123"}
    }
    

    如果您有多个符合条件的项目,请改用列表:

    POST /twitter/twit/1/_update
    {
      "script": "items_to_remove = []; foreach (item : ctx._source.list) { if (item['tweet_id'] == tweet_id) { items_to_remove.add(item); } } foreach (item : items_to_remove) {ctx._source.list.remove(item);}",
      "params": {"tweet_id": "123"}
    }
    

    【讨论】:

      【解决方案2】:

      如果有人在 2021 年仍然需要​​这个,那么这里是 ES 7 的工作版本:

      POST /users/_update/1
      {
          "script": {
              "lang": "painless",
              "source": "for (int i = 0; i < ctx._source.my_objects.length; ++i) {if (ctx._source.my_objects[i]['name'] == params['name']) {ctx._source.my_objects.remove(i);}}",
              "params": {"name": "delete_this"}
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-03-30
        • 1970-01-01
        • 2019-06-04
        • 2017-02-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多