topAggregationBuilder
时间: 2024-06-19 14:02:30 浏览: 8
`topAggregationBuilder`是Elasticsearch中的一个聚合器,用于聚合查询结果并返回排名前N的文档。下面是一个使用`topAggregationBuilder`的例子:
```python
from elasticsearch import Elasticsearch
from elasticsearch_dsl import Search
from elasticsearch_dsl.aggs import TopAgg
# 创建Elasticsearch客户端
es = Elasticsearch()
# 创建查询
s = Search(using=es, index="my_index") \
.query("match", title="python") \
.filter("range", publish_date={"gte": "2020-01-01"})
# 创建聚合器
top_agg = TopAgg("top_authors", field="author.keyword", size=10)
# 将聚合器添加到查询中
s.aggs.bucket(top_agg)
# 执行查询
response = s.execute()
# 获取聚合结果
for bucket in response.aggregations.top_authors.buckets:
print(bucket.key, bucket.doc_count)
```
上面的代码中,我们首先使用`Elasticsearch`创建了一个Elasticsearch客户端,然后使用`Search`创建了一个查询,查询了所有`title`中包含`python`,并且`publish_date`在`2020-01-01`之后的文档。接着,我们使用`TopAgg`创建了一个聚合器,该聚合器将查询结果按照`author`字段进行聚合,并返回排名前10的文档。最后,我们将聚合器添加到查询中,并执行查询。执行完查询后,我们可以通过`response.aggregations.top_authors.buckets`获取聚合结果,该结果包含了每个`author`出现的次数、排名等信息。