【问题标题】:Elasticsearch Query for field with multiple valuesElasticsearch 查询具有多个值的字段
【发布时间】:2020-02-26 05:09:40
【问题描述】:

是否可以编写一个 Elasticsearch 查询,只返回在给定字段中具有多个值的文档?我不在乎这些值是什么,只是一个字段有多个,而不是 1。

我希望查询匹配:

{
  "color": ["red", "blue"]
},
{
  "color": ["green", "yellow", "orange"]
}

但不是

{
  "color": "red"
}

理想情况下,我宁愿避免在查询中使用脚本;它们在我的集群上被禁用。

【问题讨论】:

    标签: elasticsearch


    【解决方案1】:

    我不知道不使用脚本的解决方法。但你可以选择:

    准备工作:索引一些示例文档

    POST my_index/_bulk
    {"index": {"_id": 1}}
    {"color": ["red", "blue"]}
    {"index": {"_id": 2}}
    {"color": ["green", "yellow", "orange"]}
    {"index": {"_id": 3}}
    {"color": ["grey"]}
    

    选项 1:在查询时使用脚本(“昂贵”)

    GET my_index/_search
    {
      "query": {
        "script": {
          "script": "doc.color.size() > 1"
        }
      }
    }
    

    选项 2:在索引时使用脚本(“便宜”)

    (首选方法,因为每次文档写入时脚本只执行一次)

    PUT _ingest/pipeline/set_number_of_colors
    {
      "processors": [
        {
          "script": {
            "lang": "painless",
            "source": "ctx.number_of_colors = ctx.color.size()"
          }
        }
      ]
    }
    
    POST my_index/_update_by_query?pipeline=set_number_of_colors
    
    GET my_index/_search
    {
      "query": {
        "range": {
          "number_of_colors": {"gt": 1}
        }
      }
    }
    

    您还可以将管道配置为索引的默认管道,因此您无需更改索引应用程序逻辑中的任何内容。

    【讨论】:

    • 我不会说我对它“满意”,因为我不能在集群中使用脚本,但它似乎是正确的。 :P
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-20
    • 2017-02-01
    • 1970-01-01
    • 2020-02-26
    • 2022-06-29
    • 2011-09-15
    • 2016-08-18
    相关资源
    最近更新 更多