温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

elasticsearch怎么实现搜索

发布时间:2026-10-29 08:38:23 来源:亿速云 阅读:99 作者:小樊 栏目:软件技术

Elasticsearch(ES)实现“搜索”本质上就是:往 ES 里写数据 → 建索引 → 用查询语句检索。下面从整体流程到常见搜索方式给你讲清楚。


一、Elasticsearch 搜索的基本流程

  1. 写入数据(Index)

    • 数据以 JSON 文档形式存入
    • 每个文档属于一个 Index(类似数据库表)
  2. 建立倒排索引

    • ES 自动分词、建立倒排索引
    • 这是搜索快的核心原因
  3. 执行查询(Search)

    • 通过 REST API 或客户端发送查询
    • ES 返回匹配文档 + 评分(相关性)

二、最基础的搜索方式(REST API)

1️⃣ 全文搜索(最常见)

GET /articles/_search
{
  "query": {
    "match": {
      "title": "elasticsearch 教程"
    }
  }
}

✅ 会对 title 分词并匹配
✅ 返回结果按相关性 _score 排序


2️⃣ 精确匹配(不分词)

GET /articles/_search
{
  "query": {
    "term": {
      "status": "published"
    }
  }
}

✅ 用于:

  • 状态
  • 枚举值
  • 数字、日期

3️⃣ 多字段搜索

GET /articles/_search
{
  "query": {
    "multi_match": {
      "query": "elasticsearch",
      "fields": ["title", "content"]
    }
  }
}

三、组合复杂搜索(bool 查询)

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"
      }
    }
  }
}

常用中文分词器:

  • IK
  • jieba
  • smartcn

✅ 分页搜索

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": {}
    }
  }
}

五、代码中使用(示例)

Java(RestHighLevelClient)

SearchRequest request = new SearchRequest("articles");
request.source(new SearchSourceBuilder()
    .query(QueryBuilders.matchQuery("title", "elasticsearch")));

SearchResponse response = client.search(request, RequestOptions.DEFAULT);

Python(elasticsearch-py)

from elasticsearch import Elasticsearch

es = Elasticsearch()

es.search(
    index="articles",
    query={
        "match": {
            "title": "elasticsearch"
        }
    }
)

六、搜索核心总结

能力 对应方式
全文搜索 match
精确搜索 term
多条件 bool
中文 IK 分词
排序 sort
高亮 highlight

如果你愿意,我可以:

  • 帮你设计 ES 索引结构
  • 写一个完整搜索示例(含中文)
  • 对比 ES vs MySQL 搜索
  • 讲 ES 搜索性能优化

你现在是想做哪一类搜索?

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI
助
手