
[英]How to filter the response from mongoDB, so nested arrays will include only items that meet a condition?
[英]Elasticsearch response to include items coditionally
我需要删除我在响应中获得的一些额外数据,但需要有条件地删除这些数据,因此简单的包含或排除可能不起作用
GET /houseId/_search
{
"_source": {
"include": ["name","labels"]
},
"query": {
"bool": {
"must": [
{
"terms": {
"cloud_id.keyword": [
"something"
]
}
}
]
}
}
}
上面的查询返回以下响应
{
...
"hits" : {
...
"hits" : [
{
...
"_source" : {
"name" : "peter",
"labels" : [
{
"value" : "true",
"key" : "active"
},
{
"value" : "103",
"key" : "pool-id"
}
]
}
},
{
...
"_source" : {
"name" : "john",
"labels" : [
{
"value" : "true",
"key" : "active"
},
{
"value" : "205",
"key" : "pool-id""
}
]
}
}
]
}
}
返回的文档是正确的,但是,我需要删除我在labels
字段中获得的一些额外数据。 我只想要键为pool-id
的键和值。 这样labels
可能如下所示
"labels" : {
"value" : "205",
"key" : "pool-id""
}
要仅返回labels
object 中具有"key": "pool-id"
的文档,您需要定义显式映射,并且 map labels
为嵌套类型。
然后使用带有嵌套查询的 inner_hits 仅返回匹配的nested
object。
索引映射:
{
"mappings": {
"properties": {
"labels": {
"type": "nested"
}
}
}
}
搜索查询:
{
"_source": {
"include": [
"name",
"labels"
]
},
"query": {
"bool": {
"must": [
{
"terms": {
"cloud_id.keyword": [
"something"
]
}
},
{
"nested": {
"path": "labels",
"query": {
"term": {
"labels.key.keyword": "pool-id"
}
},
"inner_hits": {}
}
}
]
}
}
}
搜索结果:
"hits": [
{
"_index": "72821655",
"_id": "1",
"_score": 0.6931471,
"_source": {
"name": "peter",
"labels": [
{
"value": "true",
"key": "active"
},
{
"value": "103",
"key": "pool-id"
}
]
},
"inner_hits": {
"labels": {
"hits": {
"total": {
"value": 1,
"relation": "eq"
},
"max_score": 0.6931471,
"hits": [
{
"_index": "72821655",
"_id": "1",
"_nested": {
"field": "labels",
"offset": 1
},
"_score": 0.6931471,
"_source": {
"value": "103",
"key": "pool-id"
}
}
]
}
}
}
},
{
"_index": "72821655",
"_id": "2",
"_score": 0.6931471,
"_source": {
"name": "john",
"labels": [
{
"value": "true",
"key": "active"
},
{
"value": "205",
"key": "pool-id" // note this
}
]
},
"inner_hits": {
"labels": {
"hits": {
"total": {
"value": 1,
"relation": "eq"
},
"max_score": 0.6931471,
"hits": [
{
"_index": "72821655",
"_id": "2",
"_nested": {
"field": "labels",
"offset": 1
},
"_score": 0.6931471,
"_source": {
"value": "205",
"key": "pool-id" // note this
}
}
]
}
}
}
}
]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.