【问题标题】:Elasticsearch: filtering on fields that matched criteriaElasticsearch:过滤匹配条件的字段
【发布时间】:2020-08-27 04:09:16
【问题描述】:

我使用的是弹性搜索 6.8.8。我的索引的映射非常复杂,因此出于解释的目的我将对其进行简化。假设我有一个在其物业中有员工的公司的索引:

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

我想搜索至少有一名员工年龄在 20 到 30 岁之间并且姓名为“Smith”的公司。

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

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

如何指定两个“过滤器”应应用于同一字段?

非常感谢!

【问题讨论】:

    标签: elasticsearch elasticsearch-dsl


    【解决方案1】:

    首先,您需要将您的employee 结构设为type nested(您需要重建索引,因为您无法将employee 的类型从object 更改为nested):

    {
      "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
                    }
                  }
                }
              ]
            }
          }
        }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-02
      • 2013-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多