嵌套查询弹性搜索

Nested Query Elastic Search

目前我正在尝试 search/filter 弹性搜索中的嵌套文档 Spring 数据。

当前文档结构是:

{
  "id": 1,
  "customername": "Cust@123",
  "policydetails": {
    "address": {
      "city": "Irvine",
      "state": "CA",
      "address2": "23994384, Out OF World",
      "post_code": "92617"
    },
    "policy_data": [
      {
        "id": 1,
        "status": true,
        "issue": "Variation Issue"
      },
      {
        "id": 32,
        "status": false,
        "issue": "NoiseIssue"
      }
    ]
  }
}

现在我们需要过滤掉有噪音问题的policy_data,如果没有有噪音问题的政策数据,policy_data在父文档中将为空。

我试过使用这个查询

{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "customername": "Cust@345"
          }
        },
        {
          "nested": {
            "path": "policiesDetails.policy_data",
            "query": {
              "bool": {
                "must": {
                  "terms": {
                    "policiesDetails.policy_data.issue": [
                      "Noise Issue"
                    ]
                  }
                }
              }
            }
          }
        }
      ]
    }
  }
}

这可以很好地过滤嵌套文档。但是如果嵌套文档没有匹配项,它会从视图中删除整个文档。

我想要的是如果嵌套过滤器不匹配:-

{
  "id": 1,
  "customername": "Cust@123",
  "policydetails": {
    "address": {
      "city": "Irvine",
      "state": "CA",
      "address2": "23994384, Out OF World",
      "post_code": "92617"
    },
    "policy_data": null
  }

如果未找到任何嵌套文档,则不会返回父文档。

您可以为 policy_data 使用 should 子句。如果找到嵌套文档,它将在 inner_hits 下返回,否则将返回父文档

{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "customername": "Cust@345"
          }
        }
      ],
      "should": [
        {
          "nested": {
            "path": "policydetails.policy_data",
            "inner_hits": {},  --> to return matched policy_data
            "query": {
              "bool": {
                "must": {
                  "terms": {
                    "policydetails.policy_data.issue": [
                      "Noise Issue"
                    ]
                  }
                }
              }
            }
          }
        }
      ]
    }
  },
  "_source": ["id","customername","policydetails.address"] --> selected fields
}

结果:

{
  "_index" : "index116",
  "_type" : "_doc",
  "_id" : "f1SxGHoB5tcHqHDtAkTC",
  "_score" : 0.2876821,
  "_source" : {
    "policydetails" : {
      "address" : {
        "city" : "Irvine",
        "address2" : "23994384, Out OF World",
        "post_code" : "92617",
        "state" : "CA"
      }
    },
    "id" : 1,
    "customername" : "Cust@123"
  },
  "inner_hits" : {
    "policydetails.policy_data" : {
      "hits" : {
        "total" : {
          "value" : 0,
          "relation" : "eq"
        },
        "max_score" : null,
        "hits" : [ ]  -->  nested query result , matched document returned
      }
    }
  }
}