【问题标题】:Return documents with an array field that contains ALL elements from a user array in Elasticsearch 6.x返回具有数组字段的文档,该数组字段包含 Elasticsearch 6.x 中用户数组中的所有元素
【发布时间】:2019-04-09 04:10:14
【问题描述】:

我所有的文档都有一个字段,tags,类型为 Array。我想使用用户输入数组搜索并返回所有具有tags 交集 的文档。元素的数量是可变的,而不是固定的大小。

示例
tags:["python", "flask", "gunicorn"]
input:["python"]

  • 这将返回true,因为input 中的所有元素都在tags 中。

tags:["nginx", "pm2"]
input:["nodejs", "nginx", "pm2", "microservice"]

  • 这将返回false,因为"nodejs""microservice" 不在tags 中。

我查看了terms 查询,但我认为它不适用于数组。

我也发现了这个,Elasticsearch array property must contain given array items,但解决方案是针对旧版本的 Elasticsearch,语法已经改变。

【问题讨论】:

    标签: arrays elasticsearch intersection


    【解决方案1】:

    我相信您正在寻找terms_set - 参考:https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-terms-set-query.html

    PUT tags
    
    POST tags/_doc
    {
      "tags": ["python", "flask", "gunicorn"]
    }
    
    POST tags/_doc
    {
      "tags": ["nginx", "pm2"]
    }
    
    GET tags/_search
    {
      "query": {
        "terms_set": {
          "tags": {
            "terms": ["nginx", "pm2"],
            "minimum_should_match_script": {
              "source": "params.num_terms"
            }
          }
        }
      }
    }
    

    返回:

      "hits" : {
        "total" : 1,
        "max_score" : 0.5753642,
        "hits" : [
          {
            "_index" : "tags",
            "_type" : "_doc",
            "_id" : "XZqN_mkB94Kxh8PwtQs_",
            "_score" : 0.5753642,
            "_source" : {
              "tags" : [
                "nginx",
                "pm2"
              ]
            }
          }
        ]
      }
    
    

    查询示例中的完整列表:

    GET tags/_search
    {
      "query": {
        "terms_set": {
          "tags": {
            "terms": ["nodejs", "nginx", "pm2", "microservice"],
            "minimum_should_match_script": {
              "source": "params.num_terms"
            }
          }
        }
      }
    }
    

    没有结果,正如预期的那样:

      "hits" : {
        "total" : 0,
        "max_score" : null,
        "hits" : [ ]
      }
    

    【讨论】:

    • 谢谢你,成功了。我无法相信我在谷歌搜索的大量工作中找不到那篇文档。
    猜你喜欢
    • 2012-08-12
    • 1970-01-01
    • 2021-10-02
    • 2013-01-22
    • 2023-03-31
    • 1970-01-01
    • 2022-01-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多