在 Elasticsearch 中实现自动补全(Auto Complete / Suggest),常见有三种主流方案,按使用频率和推荐程度排序如下:
completion 类型(官方推荐,性能最好)✅PUT /goods
{
"mappings": {
"properties": {
"title": {
"type": "text"
},
"suggest": {
"type": "completion"
}
}
}
}
POST /goods/_doc/1
{
"title": "iPhone 15 Pro",
"suggest": {
"input": ["iPhone 15", "iPhone 15 Pro", "苹果手机"]
}
}
POST /goods/_search
{
"suggest": {
"my-suggest": {
"prefix": "iph",
"completion": {
"field": "suggest"
}
}
}
}
✅ 优点:
❌ 缺点:
edge_ngram(适合中文 & 通用搜索)✅✅match 查询即可PUT /articles
{
"settings": {
"analysis": {
"analyzer": {
"autocomplete": {
"tokenizer": "autocomplete"
}
},
"tokenizer": {
"autocomplete": {
"type": "edge_ngram",
"min_gram": 1,
"max_gram": 20,
"token_chars": ["letter", "digit"]
}
}
}
},
"mappings": {
"properties": {
"title": {
"type": "text",
"analyzer": "autocomplete"
}
}
}
}
GET /articles/_search
{
"query": {
"match": {
"title": "iph"
}
}
}
✅ 优点:
❌ 缺点:
search_as_you_type(ES 7+ 推荐)✅✅✅PUT /products
{
"mappings": {
"properties": {
"name": {
"type": "search_as_you_type"
}
}
}
}
GET /products/_search
{
"query": {
"multi_match": {
"query": "iph",
"type": "bool_prefix",
"fields": ["name", "name._2gram", "name._3gram"]
}
}
}
✅ 优点:
| 方案 | 速度 | 中文 | 复杂度 | 推荐场景 |
|---|---|---|---|---|
| completion | ⭐⭐⭐⭐⭐ | ❌ | 中 | 搜索框前缀补全 |
| edge_ngram | ⭐⭐⭐⭐ | ✅ | 中 | 通用补全 |
| search_as_you_type | ⭐⭐⭐⭐ | ✅ | 低 | 新项目首选 |
如果你愿意,可以告诉我:
我可以给你一套可直接用的完整示例。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。