如何在elasticsearch中按基数计算元素?
How to count elements by cardinality in elasticsearch?
假设我有一个存储人的物理属性的映射,以及该映射中的一个字段,即用户 ID。例如:
"attributes": {
"hair_color": {
"type": "string"
},
"eyes_color": {
"type": "string"
},
"height": {
"type": "float"
},
"user_id": {
"type": "integer"
}
}
我正在尝试查询 return 有多少人具有给定的眼睛颜色。例如,它会 return 类似于 "green": 962。
我认为我需要做的是 eye_color 字段的术语桶,然后是考虑 user_id 的基数子聚合,但到目前为止我还没有成功.这是我的:
{
"aggs" : {
"eyes_color_bucket" : {
"terms" : {
"field" : "eyes_color"
}
},
"aggs":{
"count":{
"cardinality":{
"field": "eyes_color_bucket"
}
}
}
}
这当然失败了。任何帮助表示赞赏。
大功告成,试一试:
{
"size": 0,
"aggs": {
"eyes_color_bucket": {
"terms": {
"field": "eyes_color"
},
"aggs": {
"count": {
"cardinality": {
"field": "user_id"
}
}
}
}
}
}
更新
根据 Richa 下面的评论,如果您假设一个用户只有一种眼睛颜色(即没有镜片或其他颜色),您可以像这样简化聚合查询:
{
"size": 0,
"aggs": {
"eyes_color_bucket": {
"terms": {
"field": "eyes_color"
}
}
}
}
您在每个桶中得到的 doc_count
应该是具有该眼睛颜色的用户数量。感谢@Richa 提出这个问题。
假设我有一个存储人的物理属性的映射,以及该映射中的一个字段,即用户 ID。例如:
"attributes": {
"hair_color": {
"type": "string"
},
"eyes_color": {
"type": "string"
},
"height": {
"type": "float"
},
"user_id": {
"type": "integer"
}
}
我正在尝试查询 return 有多少人具有给定的眼睛颜色。例如,它会 return 类似于 "green": 962。
我认为我需要做的是 eye_color 字段的术语桶,然后是考虑 user_id 的基数子聚合,但到目前为止我还没有成功.这是我的:
{
"aggs" : {
"eyes_color_bucket" : {
"terms" : {
"field" : "eyes_color"
}
},
"aggs":{
"count":{
"cardinality":{
"field": "eyes_color_bucket"
}
}
}
}
这当然失败了。任何帮助表示赞赏。
大功告成,试一试:
{
"size": 0,
"aggs": {
"eyes_color_bucket": {
"terms": {
"field": "eyes_color"
},
"aggs": {
"count": {
"cardinality": {
"field": "user_id"
}
}
}
}
}
}
更新
根据 Richa 下面的评论,如果您假设一个用户只有一种眼睛颜色(即没有镜片或其他颜色),您可以像这样简化聚合查询:
{
"size": 0,
"aggs": {
"eyes_color_bucket": {
"terms": {
"field": "eyes_color"
}
}
}
}
您在每个桶中得到的 doc_count
应该是具有该眼睛颜色的用户数量。感谢@Richa 提出这个问题。