在Elasticsearch中查询具有嵌套对象的字段

时间:2016-03-02 04:13:39

标签: object elasticsearch nested

我有一个名为 jobdetails 的类型。该类型包含员工的专业经验相关细节。每个员工文档都有一个嵌套类型的体验文件。

"experience": 
    {

        "type": "nested",
        "properties": 
        {
            "company": {
                "type": "string"
                   },
            "title":{
                "type": "string"
                    }
        }
    }

我想知道如何获取只有“经理”或“老师”而非经验领域的“实习生”经验的员工。

对于Ex:

doc 1: experience[
{“company”:“xxx”, “title”:”manager”}, 
{“company”:“xxx”, “title”:”teacher”}, 
{“company”:“xxx”, “title”:”trainee manager”},]

doc 2: experience[{“company”:“xxx”, “title”:”manager”}]

doc 3: experience[{“company”:“xxx”, “title”:”teacher”}]

doc 4: experience[
{“company”:“xxx”, “title”:”manager”},
{“company”:“xxx”, “title”:”teacher]

所需的查询应返回doc2,doc3,doc4,但不返回doc1。

1 个答案:

答案 0 :(得分:1)

如下所示的查询应该可以解决问题,即我们正在查找experience.title字段包含managerteacher但不包含trainee的文档

{
  "query": {
    "filtered": {
      "filter": {
        "bool": {
          "must": [
            {
              "nested": {
                "path": "experience",
                "filter": {
                  "terms": {
                    "experience.title": [
                      "manager",
                      "teacher"
                    ]
                  }
                }
              }
            }
          ],
          "must_not": [
            {
              "nested": {
                "path": "experience",
                "filter": {
                  "terms": {
                    "experience.title": [
                      "trainee"
                    ]
                  }
                }
              }
            }
          ]
        }
      }
    }
  }
}