您当前的位置: 首页 >  ar

彭世瑜

暂无认证

  • 1浏览

    0关注

    2791博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

Elasticsearch数组Array类型增加、删除

彭世瑜 发布时间:2021-03-23 17:15:13 ,浏览量:1

一、Array里边的元素是String
# 创建一条数据
POST test_index/test_type/1
{
  "tags":["tag1", "tag2", "tag3"]  
}

# 查看数据
GET test_index/test_type/1


# 给 _id=1 的tags增加一个 tag5
POST test_index/test_type/1/_update
{
   "script" : {
       "source": "ctx._source.tags.add(params.tag)",
       "params" : {
          "tag" : "tag5"
       }
   }
}

# _id=1 的tags移除 tag5
POST test_index/test_type/1/_update
{
   "script" : {
       "source": "ctx._source.tags.remove(ctx._source.tags.indexOf(params.tag))",
       "params" : {
          "tag" : "tag5"
       }
   }
}

# 查询 tag1 in tags 移除tag2
POST test_index/test_type/_update_by_query
{
  "query": {
    "term": {
      "tags": "tag1"
    }
  },
  "script": {
    "source": "ctx._source.tags.remove(ctx._source.tags.indexOf(params.tag))",
    "params": {
      "tag": "tag2"
    }
  }
}
二、Array里边包含对象
# 添加一条数据
POST /blog-test/doc/AXiHn9l3CFuw25Pb9kYM
{
  "title": "Invest Money",
  "body": "Please start investing money as soon...",
  "tags": [
    "money",
    "invest"
  ],
  "published_on": "18 Oct 2017",
  "comments": [
    {
      "name": "William",
      "age": 34,
      "rating": 8,
      "comment": "Nice article..",
      "commented_on": "30 Nov 2017"
    },
    {
      "name": "John",
      "age": 38,
      "rating": 9,
      "comment": "I started investing after reading this.",
      "commented_on": "25 Nov 2017"
    },
    {
      "name": "Smith",
      "age": 33,
      "rating": 7,
      "comment": "Very good post",
      "commented_on": "20 Nov 2017"
    }
  ]
}

# 数组添加一条数据
POST /blog-test/doc/AXiHn9l3CFuw25Pb9kYM/_update
{
  "script": {
    "source": "ctx._source.comments.add(params.new_comment)",
    "params": {
      "new_comment": {
        "name": "xiang",
        "age": 25,
        "rating": 18,
        "comment": "very very good article...",
        "commented_on": "3 Nov 2018"
      }
    }
  }
}



# 数组移除一条数据
POST /blog-test/doc/AXiHn9l3CFuw25Pb9kYM/_update
{
  "script": {
    "lang": "painless",
    "source": "ctx._source.comments.removeIf(it -> it.name == 'John');"
  }
}

# 数组更新一条数据
POST /blog-test/doc/AXiHn9l3CFuw25Pb9kYM/_update
{
  "script": {
    "source": "for(e in ctx._source.comments){if (e.name == 'Smith') {e.age = 25; e.comment= 'very very good article...';}}"
  }
}

参考 Elasticsearch局部更新(数组追加) Elasticsearch 5.6.3 通过script添加、删除数组元素

关注
打赏
1665367115
查看更多评论
立即登录/注册

微信扫码登录

0.0603s