[英]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.