英文:
How do I fetch the record from the correct index of array while aggregation on ElasticSearch?
问题
I can help you with the translation. Here's the translated content:
问题描述
我有一个ElasticSearch索引,其中存储了城市的名称和它们的ID。它的结构如下:
{
"usr" : "plore113",
"cityName": "New York",
"cityId": "150p7"
},
{
"usr" : "plore114",
"cityName": "Delhi",
"cityId": "171x9"
}
我正在对这个索引运行聚合操作,其中我获取所有城市名称并将它们分桶,同时也获取它们的ID。我是通过以下方式实现的:
{
"size": 0,
"aggs": {
"cName": {
"terms": {
"field": "cityName.keyword",
"size": 1000
},
"aggs": {
"cId": {
"terms": {
"field": "cityId.keyword",
"size": 1
}
}
}
}
}
}
这个操作按预期工作,但现在我有不同的要求,我现在将会有cityName和cityId作为数组(名称和ID将与数组索引进行映射)。
示例:
cityName: ["New York", "Delhi", "Mumbai"],
cityId: ["150p7", "171x9", "183l0"]
请问如何运行相同的聚合操作,以便通过子聚合获取城市名称和它们的ID?
提前感谢。
英文:
Problem Statement
I have an ElasticSearch index that stores the Name of cities and their Ids. It looks like this:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
{
"usr" : "plore113"
"cityName": "New York",
"cityId": "150p7"
},
{
"usr" : "plore114"
"cityName": "Delhi",
"cityId": "171x9"
}
<!-- end snippet -->
I'm running an aggregation on this, where I get all the city names bucketed and I also get their Ids. I do it through this:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
{
"size": 0,
"aggs": {
"cName": {
"terms": {
"field": "cityName.keyword",
"size": 1000
},
"aggs": {
"cId": {
"terms": {
"field": "cityId.keyword",
"size": 1
}
}
}
}
}
}
<!-- end snippet -->
This is working as expected, however now I have different requirement, where I'll now have the cityName and cityId as arrays. (the name and id will be mapped with the array index).
Example:
cityName: ["New York", "Delhi", "Mumbai"],
cityId: ["150p7", "171x9", "183l0"]
How can I now run the same aggregation where I receive the cityNames, and also their Ids using the sub-aggregation?
Thanks in advance.
答案1
得分: 1
以下是翻译好的内容:
尝试使用以下代码,它创建一个运行时字段以同时过滤 cityName 和 cityId。
{
"size": 0,
"runtime_mappings": {
"city_and_id": {
"type": "keyword",
"script": {
"source": "emit(doc['cityName.keyword'].value + '-' + doc['cityId.keyword'].value)"
}
}
},
"query": {
"bool": {
"filter": [
{
"terms": {
"city_and_id": ["Delhi-171x9"]
}
}
]
}
},
"aggs": {
"cName": {
"terms": {
"field": "cityName.keyword",
"size": 1000
},
"aggs": {
"cId": {
"terms": {
"field": "cityId.keyword",
"size": 1
}
}
}
}
}
}
英文:
Try this, it builds a runtime_field to filter cityName and cityId at the same time.
{
"size": 0,
"runtime_mappings": {
"city_and_id": {
"type": "keyword",
"script": {
"source": "emit(doc['cityName.keyword'].value + '-' + doc['cityId.keyword'].value)"
}
}
},
"query": {
"bool": {
"filter": [
{
"terms": {
"city_and_id": ["Delhi-171x9"]
}
}
]
}
},
"aggs": {
"cName": {
"terms": {
"field": "cityName.keyword",
"size": 1000
},
"aggs": {
"cId": {
"terms": {
"field": "cityId.keyword",
"size": 1
}
}
}
}
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论