Elasticsearch:过滤符合条件的字段

Elasticsearch: filtering on fields that matched criteria

我正在使用 elasticsearch 6.8.8。我的索引的映射非常复杂,因此为了便于解释,我将对其进行简化。假设我有一个在其财产中有员工的公司的索引:

{
  "mappings": {
    "properties": {
      "id" : {"type" : "integer"},
      "employee" : {
        "properties" : {
          "id" : {"type" : "integer"},
          "name" : {"type" : "text"},
          "age" : {"type" : "integer"}
        }
      }     
    }
  }
}

我想搜索至少有一名员工年龄在 20 到 30 岁之间的公司 AND 其姓名为 "Smith"。

我做的查询(见下文)仅 returns 有一名员工年龄在 20 到 30 岁之间的公司和另一名员工姓名为 Smith 的公司:他们可能不是同一名员工。

GET company/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "range": {
            "employees.age": {
              "gte": 20,
              "lte": 30
            }
          }
        }
      ],
      "filter": {
        "term": {
          "employees.name": "Smith"
        }
      }
    }
  }
}

如何指定 'filters' 应应用于同一字段?

非常感谢!

首先,您需要创建 type nestedemployee 结构(您需要重建索引,因为您无法将 employee 的类型从 objectnested):

{
  "mappings": {
    "properties": {
      "id" : {"type" : "integer"},
      "employees" : {
        "type": "nested",                  <--- add this
        "properties" : {
          "id" : {"type" : "integer"},
          "name" : {"type" : "text"},
          "age" : {"type" : "integer"}
        }
      }     
    }
  }
}

完成后,您的所有数据都会重新编制索引,您可以像这样简单地利用 nested query

GET company/_search
{
  "query": {
    "nested": {
      "path": "employees",
      "query": {
        "bool": {
          "filter": [
            {
              "term": {
                "employees.name": "Smith"
              }
            },
            {
              "range": {
                "employees.age": {
                  "gte": 20,
                  "lte": 30
                }
              }
            }
          ]
        }
      }
    }
  }
}