es 实现热词搜索 代码
时间: 2023-11-23 07:06:21 浏览: 79
ElasticSearch基于Mysql热更新IK词典项目
以下是一个使用 Elasticsearch 实现热词搜索的示例代码:
```python
from elasticsearch import Elasticsearch
# 创建 Elasticsearch 客户端
es = Elasticsearch()
# 创建索引
index_name = "my_index"
body = {
"mappings": {
"properties": {
"text": {"type": "text"}
}
}
}
es.indices.create(index=index_name, body=body)
# 添加数据
data = [
{"text": "The quick brown fox jumps over the lazy dog"},
{"text": "The quick brown fox jumps over the lazy dog"},
{"text": "The quick brown fox jumps over the lazy dog"},
{"text": "The quick brown fox jumps over the lazy dog"},
{"text": "The quick brown fox jumps over the lazy dog"},
{"text": "The quick brown fox jumps over the lazy dog"},
{"text": "The quick brown fox jumps over the lazy dog"},
{"text": "The quick brown fox jumps over the lazy dog"},
{"text": "The quick brown fox jumps over the lazy dog"},
{"text": "The quick brown fox jumps over the lazy dog"},
{"text": "The quick brown fox jumps over the lazy dog"},
{"text": "The quick brown fox jumps over the lazy dog"},
{"text": "The quick brown fox jumps over the lazy dog"},
{"text": "The quick brown fox jumps over the lazy dog"},
{"text": "The quick brown fox jumps over the lazy dog"},
{"text": "The quick brown fox jumps over the lazy dog"}
]
for item in data:
es.index(index=index_name, body=item)
# 构建聚合查询
aggs_query = {
"aggs": {
"hot_words": {
"terms": {
"field": "text.keyword",
"size": 5
}
}
}
}
# 执行查询
result = es.search(index=index_name, body=aggs_query)
# 输出聚合结果
for bucket in result["aggregations"]["hot_words"]["buckets"]:
print(bucket["key"], bucket["doc_count"])
```
在这个示例中,我们首先创建了一个名为 `my_index` 的索引,并添加了一些文本数据。然后,我们构建了一个聚合查询,使用 `terms` 聚合器获取最常见的热词。最后,我们执行查询并输出聚合结果。
阅读全文