首页 > 解决方案 > 在弹性搜索中,如何匹配对象数组中的多个对象?

问题描述

我在这里按照示例进行操作:

https://www.elastic.co/guide/en/elasticsearch/reference/current/nested.html

以下查询:

GET my_index/_search
{
  "query": {
    "nested": {
      "path": "user",
      "query": {
        "bool": {
          "must": [
            { "match": { "user.first": "Alice" }},
            { "match": { "user.last":  "White" }}
          ]
        }
      }
    }
  }
}

符合预期的一条记录。假设我只想返回同时具有“John Smith”和“Alice White”作为用户的文档。

我努力了:

GET my_index/_search
{
  "query": {
    "nested": {
      "path": "user",
      "query": {
        "bool": {
          "must": [
            { "match": { "user.first": "Alice" }},
            { "match": { "user.last":  "White" }},
            { "match": { "user.first": "John" }},
            { "match": { "user.last":  "Smith" }}
          ]
        }
      }
    }
  }
}

但这会返回零结果。如何获取同时包含“Alice White”和“John Smith”的文档(应该与原始结果中返回的文档相同)?

标签: elasticsearch

解决方案


您应该使用bool 查询来组合多个子句。使用您的语法,您正在搜索在同一字段中同时包含 Alice 和 John 作为值的文档。尝试,确实:

{
  "query": {
    "bool": {
      "should": [
        {
          "nested": {
            "path": "user",
            "query": {
              "bool": {
                "must": [
                  {
                    "match": {
                      "user.first": "Alice"
                    }
                  },
                  {
                    "match": {
                      "user.last": "White"
                    }
                  }
                ]
              }
            }
          }
        },
        {
          "nested": {
            "path": "user",
            "query": {
              "bool": {
                "must": [
                  {
                    "match": {
                      "user.first": "John"
                    }
                  },
                  {
                    "match": {
                      "user.last": "Smith"
                    }
                  }
                ]
              }
            }
          }
        }
      ]
    }
  }
}

推荐阅读