elasticsearch - 仅返回对象中包含特定值的数组元素
问题描述
我在弹性搜索索引中有以下文档:
{
"type": "foo",
"components": [{
"id": "1234123", ,
"data_collections": [{
"date_time": "2020-03-02T08:14:48+00:00",
"group": "1",
"group_description": "group1",
"measures": [{
"measure_name": "MEASURE_1",
"actual": "23.34"
}, {
"measure_name": "MEASURE_2",
"actual": "5"
}, {
"measure_name": "MEASURE_3",
"actual": "string_message"
}, {
"measure_name": "MEASURE_4",
"actual": "another_string"
}
]
},
{
"date_time": "2020-03-03T08:14:48+00:00",
"group": "2",
"group_description": "group2",
"measures": [{
"measure_name": "MEASURE_1",
"actual": "23.34"
}, {
"measure_name": "MEASURE_4",
"actual": "foo"
}, {
"measure_name": "MEASURE_5",
"actual": "bar"
}, {
"measure_name": "MEASURE_6",
"actual": "4"
}
]
}
]
}
]
}
现在我正在尝试找出该文档的映射和查询,因此结果将仅包含我感兴趣的组和 measure_names。到目前为止,我可以查询,但我总是会检索整个文档,即不可行,因为措施数组可能非常大,而且大多数时候我想要一个小子集。
例如,我正在搜索带有"group": "1"
and的文档,"measure_name": "MEASURE_"
我想要实现的结果如下所示:
{
"_id": "oiqwueou8931283u12",
"_source": {
"type": "foo",
"components": [{
"id": "1234123", ,
"data_collections": [{
"date_time": "2020-03-02T08:14:48+00:00",
"group": "1",
"group_description": "group1",
"measures": [{
"measure_name": "MEASURE_1",
"actual": "23.34"
}
]
}
]
}
]
}
}
我认为接近我正在寻找的是source
参数,但据我所知,没有办法过滤像{"measure_name": {"value": "MEASURE_1"}}
谢谢。
解决方案
想到的最简单的映射是
PUT timo
{
"mappings": {
"properties": {
"components": {
"type": "nested",
"properties": {
"data_collections": {
"type": "nested",
"properties": {
"measures": {
"type": "nested"
}
}
}
}
}
}
}
}
并且搜索查询将是
GET timo/_search
{
"_source": ["inner_hits", "type", "components.id"],
"query": {
"bool": {
"must": [
{
"nested": {
"path": "components.data_collections",
"query": {
"term": {
"components.data_collections.group.keyword": {
"value": "1"
}
}
},
"inner_hits": {}
}
},
{
"nested": {
"path": "components.data_collections.measures",
"query": {
"term": {
"components.data_collections.measures.measure_name.keyword": {
"value": "MEASURE_1"
}
}
},
"inner_hits": {}
}
}
]
}
}
}
请注意inner_hits
每个子查询下的参数,并且该_source
参数是有限的,因此我们不会返回整个命中,而是只返回匹配的子组。type
并且component.id
不能在嵌套字段中“看到”,因此我们已明确包含它们。
您现在拥有所需的属性,因此进行一些后期处理即可获得所需的格式!
我不熟悉这种更清洁的方法,但如果你们中的任何一个都这样做,我会很高兴学习它。
推荐阅读
- javascript - 如何使具有特定尺寸要求的引导模态居中
- python - 执行子文件夹内的代码
- terraform - 如何动态地将参数传递给 terraform 模块并根据条件运行模块
- javascript - 使用 Javascript 阻止 target="_blank" 弹出窗口
- c - 如何在 Debian 10 中使用 QEMU 进行调试
- swift - 列表重新排序后 SwiftUI 关闭
- java - CucumberOptions 不运行功能
- java - 如何在java中从当前月份获取上个月?
- python - Python Selenium 等待函数不会引发 TimeoutException
- html - 我可以允许行内块元素跨行拆分吗?