ElasticSearch的聚合查询在Python中如何编写?(Python中ElasticSearch聚合查询的编写方法?)
编程界的探索者
2024-04-02 17:21
短信预约 Python-IT技能 免费直播动态提醒
这篇文章将为大家详细讲解有关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聚合查询的编写方法?)的详细内容,更多请关注编程学习网其它相关文章!
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341