如何对Elasticsearch中的嵌套对象进行否定查询?

时间:2019-03-28 22:03:02

标签: elasticsearch

我有一个索引,其文档包含嵌套对象的列表。映射的简化版本如下:

{
  "_doc": {
    "dynamic": "strict",
    "properties": {
      "things": {
        "type": "nested",
        "dynamic": "strict",
        "properties": {
          "name": {
            "type": "keyword"
          },
          "version": {
            "type": "keyword"
          }
        }
      }
    }
  }
}

我想获取所有没有具有 any 嵌套事物对象且具有一组特定值的文档。像

这样的查询
{
  "query": {
    "nested": {
      "path": "things",
      "query": {
        "bool": { 
          "must_not": [
            {
              "term": {
                "name": "thing1"
              }
            },
            {
              "term": {
                "version": "1.0.0"
              }
            }
          ]
        }
      }
    }
  }
}

似乎只返回所有嵌套 不匹配的文档...这意味着它仍然返回所有文档,即使那些也具有的文档匹配的嵌套对象。那么,如何正确过滤掉这些内容?

编辑:类似的查询

{
  "query": {
    "bool": {
      "must_not": [
        {
          "nested": {
            "path": "things",
            "query": {
              "bool": { 
                "must": [
                  {
                    "term": {
                      "name": "thing1"
                    }
                  },
                  {
                    "term": {
                      "version": "1.0.0"
                    }
                  }
                ]
              }
            }
          }
        }
      ]
    }
  }
}

将嵌套对象查询嵌套在must_not内的方法也不起作用,仍然只返回所有内容。

1 个答案:

答案 0 :(得分:0)

好吧,我终于自己弄明白了。事实证明,尽管已经在嵌套对象查询中明确指定了path字段,但嵌套对象的字段名称仍必须完全限定。因此,这可行:

{
  "query": {
    "nested": {
      "path": "things",
      "query": {
        "bool": { 
          "must_not": [
            {
              "term": {
                "things.name": "thing1"
              }
            },
            {
              "term": {
                "things.version": "1.0.0"
              }
            }
          ]
        }
      }
    }
  }
}