下面从概念 → 搭建 → 索引 → 查询 → 优化几个层面,系统讲一下如何用 Elasticsearch 做全文检索。
Elasticsearch(ES)是一个基于 Lucene 的分布式搜索引擎,全文检索核心流程是:
# 示例(Docker)
docker run -d \
-p 9200:9200 -p 9300:9300 \
--name es \
elasticsearch:8.11.0
访问:
http://localhost:9200
PUT /articles
{
"settings": {
"analysis": {
"analyzer": {
"default": {
"type": "ik_max_word"
}
}
}
},
"mappings": {
"properties": {
"title": {
"type": "text"
},
"content": {
"type": "text"
},
"author": {
"type": "keyword"
},
"create_time": {
"type": "date"
}
}
}
}
✅ 中文必须使用
ik_max_word或ik_smart
POST /articles/_doc
{
"title": "Elasticsearch 全文检索入门",
"content": "Elasticsearch 是一个强大的搜索引擎,支持中文全文检索。",
"author": "张三",
"create_time": "2024-01-01"
}
GET /articles/_search
{
"query": {
"match": {
"content": "全文检索"
}
}
}
✅ 会分词
✅ 按相关性排序
GET /articles/_search
{
"query": {
"multi_match": {
"query": "Elasticsearch",
"fields": ["title", "content"]
}
}
}
GET /articles/_search
{
"query": {
"match_phrase": {
"content": "中文全文检索"
}
}
}
✅ 顺序必须一致
GET /articles/_search
{
"query": {
"bool": {
"must": [
{ "match": { "content": "搜索引擎" } }
],
"filter": [
{ "term": { "author": "张三" } }
]
}
}
}
GET /articles/_search
{
"query": {
"match": {
"content": "全文检索"
}
},
"highlight": {
"fields": {
"content": {}
}
}
}
GET /articles/_search
{
"query": {
"match_all": {}
},
"sort": [
{ "create_time": "desc" }
],
"from": 0,
"size": 10
}
ik_max_word:分词细,召回高ik_smart:分词粗,性能好"content": {
"type": "text",
"index": true
}
search_after应用 → ES Client → Elasticsearch
↓
倒排索引
常见组合:
✅ 全文检索关键步骤:
如果你愿意,我可以:
你现在是准备用在哪个场景?
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。