Агрегация подсчета значений
Агрегация метрик, которая подсчитывает количество значений, извлеченных из агрегированных документов. Эти значения могут быть извлечены либо из определенных полей в документах, либо сгенерированы с помощью предоставленного скрипта. Обычно этот агрегатор используется совместно с другими агрегациями одиночных значений. Например, при вычислении среднего значения, может потребоваться количество значений, по которым вычисляется среднее.
Агрегация подсчета значений не удаляет дубликаты, поэтому даже если поле содержит дубликаты, каждое значение будет учитываться индивидуально.
resp = client.search(
index="sales",
size="0",
aggs={
"types_count": {
"value_count": {
"field": "type"
}
}
},
)
print(resp) response = client.search(
index: 'sales',
size: 0,
body: {
aggregations: {
types_count: {
value_count: {
field: 'type'
}
}
}
}
)
puts response res, err := es.Search(
es.Search.WithIndex("sales"),
es.Search.WithBody(strings.NewReader(`{
"aggs": {
"types_count": {
"value_count": {
"field": "type"
}
}
}
}`)),
es.Search.WithSize(0),
es.Search.WithPretty(),
)
fmt.Println(res, err) const response = await client.search({
index: "sales",
size: 0,
aggs: {
types_count: {
value_count: {
field: "type",
},
},
},
});
console.log(response); POST /sales/_search?size=0
{
"aggs" : {
"types_count" : { "value_count" : { "field" : "type" } }
}
} Ответ:
{
...
"aggregations": {
"types_count": {
"value": 7
}
}
} Имя агрегации (types_count выше) также служит ключом для получения результата агрегации из возвращенного ответа.
Скрипт
Если вам нужно подсчитать что-то более сложное, чем значения в одном поле, вы должны выполнить агрегацию по полю runtime.
resp = client.search(
index="sales",
size=0,
runtime_mappings={
"tags": {
"type": "keyword",
"script": "\n emit(doc['type'].value);\n if (doc['promoted'].value) {\n emit('hot');\n }\n "
}
},
aggs={
"tags_count": {
"value_count": {
"field": "tags"
}
}
},
)
print(resp) response = client.search(
index: 'sales',
body: {
size: 0,
runtime_mappings: {
tags: {
type: 'keyword',
script: "\n emit(doc['type'].value);\n if (doc['promoted'].value) {\n emit('hot');\n }\n "
}
},
aggregations: {
tags_count: {
value_count: {
field: 'tags'
}
}
}
}
)
puts response const response = await client.search({
index: "sales",
size: 0,
runtime_mappings: {
tags: {
type: "keyword",
script:
"\n emit(doc['type'].value);\n if (doc['promoted'].value) {\n emit('hot');\n }\n ",
},
},
aggs: {
tags_count: {
value_count: {
field: "tags",
},
},
},
});
console.log(response); POST /sales/_search
{
"size": 0,
"runtime_mappings": {
"tags": {
"type": "keyword",
"script": """
emit(doc['type'].value);
if (doc['promoted'].value) {
emit('hot');
}
"""
}
},
"aggs": {
"tags_count": {
"value_count": {
"field": "tags"
}
}
}
} Поля гистограмм
Когда агрегация подсчета значений вычисляется по полям гистограмм, результат агрегации является суммой всех чисел в массиве counts гистограммы.
Например, для следующего индекса, который хранит предварительно агрегированные гистограммы с метриками задержки для различных сетей:
resp = client.index(
index="metrics_index",
id="1",
document={
"network.name": "net-1",
"latency_histo": {
"values": [
0.1,
0.2,
0.3,
0.4,
0.5
],
"counts": [
3,
7,
23,
12,
6
]
}
},
)
print(resp)
resp1 = client.index(
index="metrics_index",
id="2",
document={
"network.name": "net-2",
"latency_histo": {
"values": [
0.1,
0.2,
0.3,
0.4,
0.5
],
"counts": [
8,
17,
8,
7,
6
]
}
},
)
print(resp1)
resp2 = client.search(
index="metrics_index",
size="0",
aggs={
"total_requests": {
"value_count": {
"field": "latency_histo"
}
}
},
)
print(resp2) response = client.index(
index: 'metrics_index',
id: 1,
body: {
'network.name' => 'net-1',
latency_histo: {
values: [
0.1,
0.2,
0.3,
0.4,
0.5
],
counts: [
3,
7,
23,
12,
6
]
}
}
)
puts response
response = client.index(
index: 'metrics_index',
id: 2,
body: {
'network.name' => 'net-2',
latency_histo: {
values: [
0.1,
0.2,
0.3,
0.4,
0.5
],
counts: [
8,
17,
8,
7,
6
]
}
}
)
puts response
response = client.search(
index: 'metrics_index',
size: 0,
body: {
aggregations: {
total_requests: {
value_count: {
field: 'latency_histo'
}
}
}
}
)
puts response {
res, err := es.Index(
"metrics_index",
strings.NewReader(`{
"network.name": "net-1",
"latency_histo": {
"values": [
0.1,
0.2,
0.3,
0.4,
0.5
],
"counts": [
3,
7,
23,
12,
6
]
}
}`),
es.Index.WithDocumentID("1"),
es.Index.WithPretty(),
)
fmt.Println(res, err)
}
{
res, err := es.Index(
"metrics_index",
strings.NewReader(`{
"network.name": "net-2",
"latency_histo": {
"values": [
0.1,
0.2,
0.3,
0.4,
0.5
],
"counts": [
8,
17,
8,
7,
6
]
}
}`),
es.Index.WithDocumentID("2"),
es.Index.WithPretty(),
)
fmt.Println(res, err)
}
{
res, err := es.Search(
es.Search.WithIndex("metrics_index"),
es.Search.WithBody(strings.NewReader(`{
"aggs": {
"total_requests": {
"value_count": {
"field": "latency_histo"
}
}
}
}`)),
es.Search.WithSize(0),
es.Search.WithPretty(),
)
fmt.Println(res, err)
} const response = await client.index({
index: "metrics_index",
id: 1,
document: {
"network.name": "net-1",
latency_histo: {
values: [0.1, 0.2, 0.3, 0.4, 0.5],
counts: [3, 7, 23, 12, 6],
},
},
});
console.log(response);
const response1 = await client.index({
index: "metrics_index",
id: 2,
document: {
"network.name": "net-2",
latency_histo: {
values: [0.1, 0.2, 0.3, 0.4, 0.5],
counts: [8, 17, 8, 7, 6],
},
},
});
console.log(response1);
const response2 = await client.search({
index: "metrics_index",
size: 0,
aggs: {
total_requests: {
value_count: {
field: "latency_histo",
},
},
},
});
console.log(response2); PUT metrics_index/_doc/1
{
"network.name" : "net-1",
"latency_histo" : {
"values" : [0.1, 0.2, 0.3, 0.4, 0.5],
"counts" : [3, 7, 23, 12, 6]
}
}
PUT metrics_index/_doc/2
{
"network.name" : "net-2",
"latency_histo" : {
"values" : [0.1, 0.2, 0.3, 0.4, 0.5],
"counts" : [8, 17, 8, 7, 6]
}
}
POST /metrics_index/_search?size=0
{
"aggs": {
"total_requests": {
"value_count": { "field": "latency_histo" }
}
}
} Для каждого поля гистограммы агрегация подсчета значений просуммирует все числа в массиве counts <1>. В конечном итоге она добавит все значения для всех гистограмм и вернет следующий результат:
{
...
"aggregations": {
"total_requests": {
"value": 97
}
}
}
© 2023-2025 Elasticsearch
As of September 2024, Elasticsearch is available under a choice of three licenses: the Server Side Public License (SSPL), the Elastic License, or the AGPLv3 (OSI approved).
Elasticsearch and the Elasticsearch logo are trademarks of Elasticsearch B.V., registered in the U.S. and in other countries.
https://www.elastic.co/guide/en/elasticsearch/reference/8.17/search-aggregations-metrics-valuecount-aggregation.html