我试图将统计应用程序从纯MySQL迁移到MySQL + ElasticSearch v6,我找不到如何正确地进行聚合。 因为一个例子比smocky解释更好,这里是我的数据的摘录:
映射:
{
"mappings": {
"sample_type": {
"properties": {
"hash": {
"type": "keyword"
},
"zone": {
"type": "keyword"
},
"labo_id": {
"type": "integer"
},
"raw_results": {
"type": "nested",
"properties": {
"result": {
"type": "keyword"
},
"code": {
"type": "keyword"
}
}
}
}
}
}
}
索引内容:
{
"hits": [
{
"_index": "my_index",
"_type": "my_type",
"_id": "faf3294351e84ab0bb08becf2025a0f6",
"_score": 1,
"_source": {
"hash": "hash1",
"labo_id": 1,
"zone": "22",
"raw_results": [
{
"result": "S",
"code": "AMX"
},
{
"result": "S",
"code": "AMC"
}
]
}
},
{
"_index": "my_index",
"_type": "my_type",
"_id": "faf3294351e84ab0bb08becf2025a0f6",
"_score": 1,
"_source": {
"hash": "hash2",
"labo_id": 1,
"zone": "22",
"raw_results": [
{
"result": "R",
"code": "AMX"
},
{
"result": "S",
"code": "AMC"
}
]
}
},
{
"_index": "my_index",
"_type": "my_type",
"_id": "faf3294351e84ab0bb08becf2025a0f6",
"_score": 1,
"_source": {
"hash": "hash3",
"labo_id": 1,
"zone": "56",
"raw_results": [
{
"result": "S",
"code": "AMX"
},
{
"result": "R",
"code": "AMC"
}
]
}
},
{
"_index": "my_index",
"_type": "my_type",
"_id": "faf3294351e84ab0bb08becf2025a0f6",
"_score": 1,
"_source": {
"hash": "hash4",
"labo_id": 1,
"zone": "56",
"raw_results": [
{
"result": "S",
"code": "AMX"
},
{
"result": "R",
"code": "AMC"
}
]
}
}
]
}
我试图实现的结果:
code | result | zone | count
---------------------------------
AMX | R | 22 | 1
AMX | S | 22 | 1
AMX | R | 56 | 0
AMX | S | 56 | 2
| | |
AMC | R | 22 | 0
AMC | S | 22 | 2
AMC | R | 56 | 2
AMC | S | 56 | 0
我尝试计算每个代码的结果值,按区域分组。什么是检索此结果的正确方法?
不要犹豫,告诉我是否可以使用更好的索引结构。
谢谢你, JM
编辑2018-04-02
我找到了一个可以完成这项工作的查询:
{
"size": 0,
"aggs": {
"zone": {
"terms": {
"field": "zone"
},
"aggs": {
"raw_results": {
"nested": {
"path": "raw_results"
},
"aggs": {
"code": {
"terms": {
"field": "raw_results.code"
},
"aggs": {
"result": {
"terms": {
"field": "raw_results.result"
}
}
}
}
}
}
}
}
}
}
我可以解析此结果以获取我的结果数组,但我将继续搜索以正确顺序给出聚合的查询。