这篇文章将为大家详细讲解有关ElasticSearch的聚合查询在Python中如何编写?(Python中ElasticSearch聚合查询的编写方法?),小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。
1. 获取聚合结果
from elasticsearch import Elasticsearch
es = Elasticsearch()
res = es.search(
index="my-index",
body={
"size": 0,
"aggs": {
"my_agg": {
"terms": {"field": "my_field"}
}
}
}
)
for bucket in res["aggregations"]["my_agg"]["buckets"]:
print(bucket["key"], bucket["doc_count"])
2. 按字段分组
res = es.search(
index="my-index",
body={
"size": 0,
"aggs": {
"my_agg": {
"terms": {"field": "my_field"}
}
}
}
)
3. 按多个字段分组
res = es.search(
index="my-index",
body={
"size": 0,
"aggs": {
"my_agg": {
"terms": {
"fields": ["my_field1", "my_field2"]
}
}
}
}
)
4. 按范围聚合
res = es.search(
index="my-index",
body={
"size": 0,
"aggs": {
"my_agg": {
"range": {
"field": "my_field",
"ranges": [
{"from": 0, "to": 10},
{"from": 10, "to": 20},
{"from": 20, "to": 30}
]
}
}
}
}
)
5. 按直方图聚合
res = es.search(
index="my-index",
body={
"size": 0,
"aggs": {
"my_agg": {
"histogram": {
"field": "my_field",
"interval": 10
}
}
}
}
)
6. 按嵌套聚合
res = es.search(
index="my-index",
body={
"size": 0,
"aggs": {
"my_agg": {
"nested": {
"path": "my_nested_field"
},
"aggs": {
"my_nested_agg": {
"terms": {"field": "my_nested_field.my_subfield"}
}
}
}
}
}
)
7. 按子聚合
res = es.search(
index="my-index",
body={
"size": 0,
"aggs": {
"my_agg": {
"terms": {"field": "my_field"},
"aggs": {
"my_sub_agg": {
"max": {"field": "my_sub_field"}
}
}
}
}
}
)
8. 按桶过滤器
res = es.search(
index="my-index",
body={
"size": 0,
"aggs": {
"my_agg": {
"terms": {"field": "my_field"},
"aggs": {
"my_sub_agg": {
"max": {"field": "my_sub_field"}
},
"my_bucket_filter": {
"filter": {"range": {"my_field": {"gt": 10}}}
}
}
}
}
}
)
9. 按脚本聚合
res = es.search(
index="my-index",
body={
"size": 0,
"aggs": {
"my_agg": {
"terms": {"script": {"inline": "doc["my_field"].value * 2"}}
}
}
}
)
10. 按桶排序
res = es.search(
index="my-index",
body={
"size": 0,
"aggs": {
"my_agg": {
"terms": {"field": "my_field"},
"order": {
"_count": "desc"
}
}
}
}
)
以上就是ElasticSearch的聚合查询在Python中如何编写?(Python中ElasticSearch聚合查询的编写方法?)的详细内容,更多请关注编程学习网其它相关文章!