Elasticsearch:如果任何嵌套对象字段与术语值匹配,则不 return 记录

Elasticsearch: don't return document if any of nested object field matches term value

我努力编写一个查询,如果它的任何嵌套对象字段值与查询中传递的术语值相匹配,则该查询不应 return 文档。

文档样本:

 {
      "id": 1,
      "test": "name",
      "rules": [
        {
          "id": 2,
          "name": "rule3",
          "questionDetailConditionalRules": [
            {
              "questionDetailId": 1
            },
            {
              "questionDetailId": 2
            }
          ]
        },
        {
          "id": 3,
          "name": "rule3",
          "questionDetailConditionalRules": [
            {
              "questionDetailId": 4
            },
            {
              "questionDetailId": 5
            }
          ]
        }
      ]
    }

rule 字段有嵌套类型

我的嵌套搜索查询是:

{
  "query": {
    "nested": {
      "path": "rules",
      "query": {
        "bool": {
          "must_not": [
            {
              "terms": {
                "rules.questionDetailConditionalRules.questionDetailId": [
                  1
                ]
              }
            }
          ]
        }
      }
    }
  }
}

预期结果:不应return编辑文档 实际结果:文档已 returned。

我应该在查询中遗漏任何内容吗?

能够重现并修复您的问题,请逐步找到解决方案以使其正常工作。 您需要将 nested 移动到 must_not 块中并对您的查询进行一些修改。

索引定义

{
    "mappings" :{
        "properties" :{
            "rules" :{
                "type" : "nested"
            }
        }
    }
}

索引您的示例文档

{
    "rules": [
        {
            "id": 2,
            "name": "rule3",
            "questionDetailConditionalRules": [
                {
                    "questionDetailId": 1
                },
                {
                    "questionDetailId": 2
                }
            ]
        },
        {
            "id": 3,
            "name": "rule3",
            "questionDetailConditionalRules": [
                {
                    "questionDetailId": 4
                },
                {
                    "questionDetailId": 5
                }
            ]
        }
    ]
}

搜索查询

{
    "query": {
        "bool": {
            "must_not": [
                {
                    "nested": {
                        "path": "rules",  --> note `nested` is inside the `must_not` block.
                        "query": {
                            "bool": {
                                "filter": [
                                    {
                                        "term": {
                                            "rules.questionDetailConditionalRules.questionDetailId": 1
                                        }
                                    }
                                ]
                            }
                        }
                    }
                }
            ]
        }
    }
}

搜索结果

"hits": {
        "total": {
            "value": 0,
            "relation": "eq"
        },
        "max_score": null,
        "hits": []
    }

注意:您可以在 this link.

中找到更多信息