我发现的唯一接近的是:Multiple group-by in Elasticsearch
基本上我正在尝试获得与以下MySql
查询等效的 ES:
select gender, age_range, count(distinct profile_id) as count
FROM TABLE group by age_range, gender
年龄和性别本身很容易获得:
{
"query": {
"match_all": {}
},
"facets": {
"ages": {
"terms": {
"field": "age_range",
"size": 20
}
},
"gender_by_age": {
"terms": {
"fields": [
"age_range",
"gender"
]
}
}
},
"size": 0
}
这使:
{
"ages": {
"_type": "terms",
"missing": 0,
"total": 193961,
"other": 0,
"terms": [
{
"term": 0,
"count": 162643
},
{
"term": 3,
"count": 10683
},
{
"term": 4,
"count": 8931
},
{
"term": 5,
"count": 4690
},
{
"term": 6,
"count": 3647
},
{
"term": 2,
"count": 3247
},
{
"term": 1,
"count": 120
}
]
},
"total_gender": {
"_type": "terms",
"missing": 0,
"total": 193961,
"other": 0,
"terms": [
{
"term": 1,
"count": 94799
},
{
"term": 2,
"count": 62645
},
{
"term": 0,
"count": 36517
}
]
}
}
但现在我需要一些看起来像这样的东西:
[breakdown_gender] => Array
(
[1] => Array
(
[0] => 264
[1] => 1
[2] => 6
[3] => 67
[4] => 72
[5] => 40
[6] => 23
)
[2] => Array
(
[0] => 153
[2] => 2
[3] => 21
[4] => 35
[5] => 22
[6] => 11
)
)
请注意,这0,1,2,3,4,5,6
是年龄范围的“映射”,因此它们实际上意味着一些东西:) 而不仅仅是数字。例如,性别[1](即“男性”)细分为年龄范围 [0](即“18 岁以下”),计数为 246。