温馨提示×

温馨提示×

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

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

怎样用elasticsearch做全文检索

发布时间:2026-09-16 19:52:35 来源:亿速云 阅读:99 作者:小樊 栏目:软件技术

下面从概念 → 搭建 → 索引 → 查询 → 优化几个层面,系统讲一下如何用 Elasticsearch 做全文检索。


一、Elasticsearch 全文检索基本原理

Elasticsearch(ES)是一个基于 Lucene 的分布式搜索引擎,全文检索核心流程是:

  1. 分词(Analysis)
    • 文本 → 词条(term)
    • 中文常用 IK、jieba 分词器
  2. 建倒排索引(Inverted Index)
    • 词条 → 文档 ID 列表
  3. 查询时
    • 查询语句先分词
    • 再用倒排索引快速匹配
  4. 相关性打分(BM25)
    • 根据词频、逆文档频率等计算 score

二、环境准备

1. 安装 Elasticsearch

# 示例(Docker)
docker run -d \
  -p 9200:9200 -p 9300:9300 \
  --name es \
  elasticsearch:8.11.0

访问:

http://localhost:9200

三、创建索引(重点)

1. 创建索引(指定分词器)

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

五、全文检索查询方式

1. match(最常用)

GET /articles/_search
{
  "query": {
    "match": {
      "content": "全文检索"
    }
  }
}

✅ 会分词
✅ 按相关性排序


2. multi_match(多字段)

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

3. match_phrase(短语匹配)

GET /articles/_search
{
  "query": {
    "match_phrase": {
      "content": "中文全文检索"
    }
  }
}

✅ 顺序必须一致


4. bool 组合查询(实战常用)

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
}

八、性能优化建议

1. 分词器选择

  • ik_max_word:分词细,召回高
  • ik_smart:分词粗,性能好

2. 只索引需要的字段

"content": {
  "type": "text",
  "index": true
}

3. 避免深分页

  • 使用 search_after

4. 冷热分离 / 分片合理

  • 单索引不超过 50GB

九、典型架构

应用 → ES Client → Elasticsearch
                   ↓
               倒排索引

常见组合:

  • 日志:ES + Logstash + Kibana
  • 搜索:MySQL / MongoDB + ES

十、简单总结

✅ 全文检索关键步骤:

  1. 合理建索引
  2. 选对分词器
  3. 使用 match / bool 查询
  4. 高亮 + 排序

如果你愿意,我可以:

  • 给你 Spring Boot + ES 示例
  • 或 千万级数据搜索优化方案
  • 或 IK 分词器详细配置

你现在是准备用在哪个场景?

向AI问一下细节

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

AI
助
手