Elasticsearch(ES)实现“搜索”本质上就是:往 ES 里写数据 → 建索引 → 用查询语句检索。下面从整体流程到常见搜索方式给你讲清楚。
写入数据(Index)
建立倒排索引
执行查询(Search)
GET /articles/_search
{
"query": {
"match": {
"title": "elasticsearch 教程"
}
}
}
✅ 会对 title 分词并匹配
✅ 返回结果按相关性 _score 排序
GET /articles/_search
{
"query": {
"term": {
"status": "published"
}
}
}
✅ 用于:
GET /articles/_search
{
"query": {
"multi_match": {
"query": "elasticsearch",
"fields": ["title", "content"]
}
}
}
GET /articles/_search
{
"query": {
"bool": {
"must": [
{ "match": { "title": "elasticsearch" } }
],
"filter": [
{ "term": { "status": "published" } }
],
"must_not": [
{ "term": { "deleted": true } }
]
}
}
}
含义:
must:必须匹配(影响评分)filter:必须匹配(不影响评分)must_not:不能匹配PUT /articles
{
"mappings": {
"properties": {
"content": {
"type": "text",
"analyzer": "ik_max_word"
}
}
}
}
常用中文分词器:
GET /articles/_search
{
"from": 0,
"size": 10,
"query": {
"match_all": {}
}
}
⚠️ 深度分页性能差,推荐 search_after
GET /articles/_search
{
"sort": [
{ "publish_time": "desc" }
]
}
GET /articles/_search
{
"query": {
"match": { "content": "elasticsearch" }
},
"highlight": {
"fields": {
"content": {}
}
}
}
SearchRequest request = new SearchRequest("articles");
request.source(new SearchSourceBuilder()
.query(QueryBuilders.matchQuery("title", "elasticsearch")));
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
from elasticsearch import Elasticsearch
es = Elasticsearch()
es.search(
index="articles",
query={
"match": {
"title": "elasticsearch"
}
}
)
| 能力 | 对应方式 |
|---|---|
| 全文搜索 | match |
| 精确搜索 | term |
| 多条件 | bool |
| 中文 | IK 分词 |
| 排序 | sort |
| 高亮 | highlight |
如果你愿意,我可以:
你现在是想做哪一类搜索?
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。