Elasticsearch 6.7 - 如何过滤必须包含给定数组项的嵌套数组字段

Elasticsearch 6.7 - How to filter a nested array field that must contain given array items

我正在尝试通过 elasticsearch(版本 6.7.1)中的嵌套数组对象中的字段过滤搜索结果。

具体尝试仅 return 包含单个字段过滤器中所有术语的结果(通常这将存储为对象数组),在 elasticsearch 中这已存储为嵌套类型,请参阅下面的数据结构。

映射:

{
  ...
  "mappings": {
    "doc": {
      "properties": {
        ...
        "dimensions": {
          "type": "nested",
          "properties": {
            ...
            "name": {
              "fields": {
                "raw": {
                  "analyzer": "raw_analyzer",
                  "type": "text",
                  "index_options": "docs",
                  "norms": false
                }
              },
              "type": "keyword"
            }
          }
        }
      }
    }
  }
}

示例文档:

文档 1:

{
  ...
  "dimensions" : [
    {
      "label" : "time",
      "name" : "time"
    },
    {
      "label" : "geography",
      "name" : "geography"
    },
    {
      "label" : "statistics",
      "name" : "statistics"
    }
  ]
}

文档 2:

{
  ...
  "dimensions" : [
    {
      "label" : "time",
      "name" : "time"
    },
    {
      "label" : "geography",
      "name" : "geography"
    },
    {
      "label" : "Age groups",
      "name" : "agegroups"
    }
  ]
}

查询是:

{
  "query": {
    "bool": {
      "filter": [
        {
          "nested": {
            "path": "dimensions",
            "query": [
              {
                "terms": {
                  "dimensions.name": [
                    "time",
                    "statistics"
                  ],
                }
              }
            ]
          }
        }
      ]
    }
  }
}

由于成功匹配 dimensions.name.

中的至少一个过滤条件,此查询 return 包含文档 1 和 2

我想要实现的是仅 return 文档 1,因为它匹配所有术语。逻辑是,如果缺少 dimensions.name 字段的 1 个或多个过滤条件,则 NOT return 文档。

我已经使用 minimum_should_matchexecution 尝试了上述查询的多种变体,但我相信这些是针对旧版本的 elasticsearch。

另外我想知道我是否应该以更好的方式对数据建模以实现这一目标。

您可以通过 must 查询代替 filter

来实现同样的效果
{
  "query": {
    "bool": {
      "must": [
        {
          "nested": {
            "path": "dimensions",
            "query": [
              {
                "term": {
                  "dimensions.name": "time"
                }
              }
            ]
          }
        },
        {
          "nested": {
            "path": "dimensions",
            "query": [
              {
                "term": {
                  "dimensions.name": "statistics"
                }
              }
            ]
          }
        }
      ]
    }
  }
}

根据 doc,您正在匹配一个术语,因此它应该是查询上下文的一部分。所以 must 完成 query context 的工作。