elasticsearch 聚合显示占比代码
时间: 2024-02-28 22:31:15 浏览: 16
以下是一个使用 Elasticsearch 聚合显示占比的示例代码:
```python
from elasticsearch import Elasticsearch
es = Elasticsearch()
# 构建聚合查询
aggs = {
"group_by_state": {
"terms": {"field": "state.keyword"},
"aggs": {
"group_by_city": {
"terms": {"field": "city.keyword"}
}
}
}
}
# 执行查询
result = es.search(
index="your_index",
body={"size": 0, "aggs": aggs}
)
# 解析结果并输出占比
total = result["hits"]["total"]["value"]
for state in result["aggregations"]["group_by_state"]["buckets"]:
state_name = state["key"]
state_count = state["doc_count"]
state_percent = state_count / total * 100
print(f"{state_name}: {state_percent:.2f}%")
for city in state["group_by_city"]["buckets"]:
city_name = city["key"]
city_count = city["doc_count"]
city_percent = city_count / total * 100
print(f"- {city_name}: {city_percent:.2f}%")
```
这里的查询是以 state 和 city 两个字段分组,然后计算每个分组的文档数占总文档数的比例。输出的结果类似于:
```
California: 50.00%
- Los Angeles: 20.00%
- San Francisco: 30.00%
New York: 30.00%
- New York City: 20.00%
- Buffalo: 10.00%
Texas: 20.00%
- Austin: 10.00%
- Houston: 10.00%
```