目前,我正在尝试搜索/过滤Elastic Search Spring Data中的嵌套文档。
当前文档结构为:
{
"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
}发布于 2021-06-17 14:50:51
如果找不到任何嵌套文档,则不会返回父文档。
您可以对policy_data使用clause子句。如果找到嵌套文档,则在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
}
}
}
}https://stackoverflow.com/questions/68004266
复制相似问题