[英]Count part of documents in elastic search
我想在弹性搜索中获取学生索引的分数为:
为了:
1 年级:计数 = 4,
2 年级:计数 = 1
3 年级:计数 = 1
4 年级:计数 = 1
使用以下查询:
{
"aggs":
{
"grade":
{
"terms":
{
"field": "marks.grade"
}
}
}
}
Output:
{
"took": 9,
"timed_out": false,
"_shards":
{
"total": 1,
"successful": 1,
"skipped": 0,
"failed": 0
},
"hits":
{
"total":
{
"value": 2,
"relation": "eq"
},
"max_score": 1.0,
"hits":
[
{
"_index": "student",
"_type": "doc",
"_id": "001",
"_score": 1.0,
"_source":
{
"name": "abc",
"marks":
[
{
"grade": 1,
"score": 95
},
{
"grade": 2,
"score": 75
},
{
"grade": 2,
"score": 72
},
{
"grade": 3,
"score": 55
}
]
}
},
{
"_index": "student",
"_type": "doc",
"_id": "002",
"_score": 1.0,
"_source":
{
"name": "xyz",
"marks":
[
{
"grade": 4,
"score": 35
},
{
"grade": 2,
"score": 79
},
{
"grade": 2,
"score": 65
}
]
}
}
]
},
"aggregations":
{
"grade":
{
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 0,
"buckets":
[
{
"key": 2,
"doc_count": 2
},
{
"key": 1,
"doc_count": 1
},
{
"key": 3,
"doc_count": 1
},
{
"key": 4,
"doc_count": 1
}
]
}
}
}
在这里,它仅将 2 级计为 2 而不是 4。
是否有任何查询可以将 output 2 年级计为 4?
{
"size":0,
"aggs": {
"grade": {
"terms": {
"field": "marks.grade"
},
"aggs": {
"count_of_grade": {
"cardinality": {
"field": "marks.grade"
}
}
}
}
}
}
响应将是
"aggregations": {
"grade": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 0,
"buckets": [
{
"key": 2,
"doc_count": 2,
"count_of_grade": {
"value": 4
}
},
{
"key": 1,
"doc_count": 1,
"count_of_grade": {
"value": 3
}
},
{
"key": 3,
"doc_count": 1,
"count_of_grade": {
"value": 3
}
},
{
"key": 4,
"doc_count": 1,
"count_of_grade": {
"value": 2
}
}
]
}
}
您可以通过嵌套marks
数组来做到这一点。 这是一个示例映射:
{
"mappings": {
"properties": {
"marks": { "type": "nested" }
}
}
}
您可以进行嵌套聚合:
{
"size": 0,
"aggs": {
"counts": {
"nested": {
"path": "marks"
},
"aggs": {
"counts": {
"terms": {
"field": "marks.grade",
"size": 10
}
}
}
}
}
}
这是聚合的结果:
{
"key" : 2,
"doc_count" : 4
},
{
"key" : 1,
"doc_count" : 1
},
{
"key" : 3,
"doc_count" : 1
},
{
"key" : 4,
"doc_count" : 1
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.