2026.6.12
Elasticsearch全文搜索引擎入门
今日学习
今天学习了Elasticsearch全文搜索引擎的使用。深入理解了ES的核心概念:Index索引、Document文档、Shard分片、Replica副本。学习掌握了ES的倒排索引原理,以及如何设计mapping定义字段类型和分词器。特别学习了IK中文分词器的配置,以及在中文环境下的搜索优化。
代码实践
为应急演练系统配置了Elasticsearch作为搜索引擎:将演练计划、应急预案等数据同步到ES,实现了高效的全文搜索功能(支持中文分词、模糊匹配、高亮显示)。搜索响应时间从200ms降低到了20ms以内,大幅提升了用户体验。
# Elasticsearch索引映射
mapping = {
"mappings": {
"properties": {
"plan_no": {"type": "keyword"},
"project_name": {"type": "text", "analyzer": "ik_max_word"},
"content": {"type": "text", "analyzer": "ik_max_word"},
"department": {"type": "keyword"},
"status": {"type": "integer"},
"create_time": {"type": "date"}
}
}
}
# 全文搜索实现
def search_plans(keyword: str, page: int = 1, size: int = 10):
query = {
"query": {
"multi_match": {
"query": keyword,
"fields": ["project_name^2", "content", "reason"]
}
},
"highlight": {
"fields": {"content": {}}
}
}
return es.search(index="drill_plans", body=query)
今日代码量
- ES映射配置:50行
- Python客户端代码:120行
- Docker Compose集成:30行
- 同步脚本:80行
- 今日总代码:280行
学习总结
Elasticsearch是处理海量数据全文检索的利器,配合IK中文分词器可以提供优秀的搜索体验。
浙公网安备 33010602011771号