Python中如何使用Elasticsearch实现全站检索
求各位大佬帮忙,es 怎么实现全站检索
Python中如何使用Elasticsearch实现全站检索
7 回复
阮一峰有个 es 的基础教程可以看看,当然我之前也写过一些博客关于 es 的
要在Python里用Elasticsearch搞全站检索,核心就两步:把数据灌进去(索引),然后搜出来。下面给你个完整能跑的demo。
首先,得装库,用pip install elasticsearch。假设你本地或者某个服务器已经跑着一个Elasticsearch实例了。
1. 建立连接和索引
from elasticsearch import Elasticsearch
from elasticsearch.helpers import bulk
# 连接到ES,这里假设是本地默认端口
es = Elasticsearch(["http://localhost:9200"])
# 定义索引的mapping,就是告诉ES你的数据长啥样,该怎么处理
index_name = "website_content"
mapping = {
"mappings": {
"properties": {
"title": {"type": "text", "analyzer": "ik_max_word", "search_analyzer": "ik_smart"}, # 用了中文分词器
"content": {"type": "text", "analyzer": "ik_max_word", "search_analyzer": "ik_smart"},
"url": {"type": "keyword"}, # 精确匹配,不分词
"publish_date": {"type": "date"}
}
}
}
# 如果索引存在,先删掉(生产环境别这么干!)
if es.indices.exists(index=index_name):
es.indices.delete(index=index_name)
# 创建索引
es.indices.create(index=index_name, body=mapping)
2. 准备和索引数据 全站数据可能来自数据库或者爬虫,这里模拟一下。
# 模拟一些网页数据
documents = [
{
"title": "Python入门教程",
"content": "本文介绍Python基础语法和数据类型。",
"url": "https://example.com/python-basic",
"publish_date": "2023-10-01"
},
{
"title": "Elasticsearch全文搜索指南",
"content": "学习如何使用Elasticsearch构建强大的搜索引擎。",
"url": "https://example.com/es-search",
"publish_date": "2023-10-15"
},
{
"title": "Python与Elasticsearch集成",
"content": "讲解如何在Python应用中操作Elasticsearch进行数据检索。",
"url": "https://example.com/python-es",
"publish_date": "2023-10-20"
}
]
# 批量索引数据,高效一点
actions = [
{
"_index": index_name,
"_source": doc
}
for doc in documents
]
bulk(es, actions)
# 等一小会儿让数据刷新可查
es.indices.refresh(index=index_name)
3. 执行搜索
这是最关键的搜索部分,用multi_match查询可以同时搜多个字段。
def full_site_search(query_string):
search_body = {
"query": {
"multi_match": {
"query": query_string,
"fields": ["title^2", "content"], # title字段权重更高
"type": "best_fields" # 匹配最佳字段
}
},
"highlight": { # 高亮显示匹配片段
"fields": {
"title": {},
"content": {}
}
}
}
response = es.search(index=index_name, body=search_body)
return response["hits"]["hits"]
# 搜一下
results = full_site_search("Python 搜索")
for hit in results:
print(f"标题: {hit['_source']['title']}")
print(f"URL: {hit['_source']['url']}")
# 打印高亮结果
if 'highlight' in hit:
if 'title' in hit['highlight']:
print(f"标题高亮: {hit['highlight']['title'][0]}")
if 'content' in hit['highlight']:
print(f"内容高亮: {hit['highlight']['content'][0]}")
print("-" * 40)
简单总结:流程就是连ES、建索引(定义好字段类型和分词)、灌数据、用multi_match查询来搜。中文记得用ik分词器。
他问的应该是 elasticsearch。
建议楼主看看「提问的智慧」。
如果楼主是处于对这一块比较模糊的阶段:是需要人为设计哪些数据放 ES,哪些地方用 ES 的。所以要整理“全站”包括哪些内容,设计合理的结构把这些都同步进 ES,然后获取的地方改从 ES 取。
我说的就是 elasticsearch 啊,不知道您理解成啥了呢?
啊,sorry 下意识看错了
我也是先反应到阮的 es6.ruan…了,才发现阮也写过 elasticsearch 的文章
btw,这问题提得那么大,就好像在问「我想做一个淘宝,需要做什么」

