Elasticsearch-如何添加术语?

发布于 2021-02-01 11:51:20

有没有一种方法可以将条件附加到值数组中?

例如,如果我的文档如下所示:

{
   "items": ["item1", "item2", "item3"]
}

我想在其后面附加“ item4”和“ item5”。

我必须在2个查询中这样做吗?一个加载当前值列表,然后更新该列表?还是有一种更优雅的方式让我在一个查询中附加这些项目?

我正在尝试使用Elastic4s做到这一点:

client.execute(ElasticDsl.update id id in indexName / documentType script {
  script(s"ctx._source.items += tag").params(Map("tag"->"item4"))
})

为了使用上面的代码片段,我需要启用groovy脚本,而且我不确定如何对多个项目执行此操作。

任何想法?

关注者
0
被浏览
123
1 个回答
  • 面试哥
    面试哥 2021-02-01
    为面试而生,有面试问题,就找面试哥。

    这是如何实现此目标的完整示例。

    合并新值到数组,并在之后使其唯一:

    DELETE test/test/1
    
    POST test/test/1
    {
      "terms":["item1", "item2", "item3"]
    }
    
    GET test/test/1
    
    POST test/test/1/_update
    {
         "script" : " ctx._source.terms << newItems; ctx._source.terms = ctx._source.terms.flatten().unique()",
         "params" : {
             "newItems" : ["a","b"]
         }
    }
    

    确保在服务器配置中启用了脚本

    user:/etc/elasticsearch# head elasticsearch.yml 
    script.inline: true
    script.indexed: true
    ...
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看