SpringBoot3 整合 Elasticsearch
1. ElasticSearch
1.1 ES
(1)ES 是一个开源的分布式搜索和分析引擎,专为处理大模型数据而设计,它能够实现近乎实时的数据检索、分析和可视化,广泛用于全文搜索、日志分析和监控(RLK Stack)、数据分析等领域。
(2)核心概念
| Index(索引) | 类似数据库中的“表” |
| Document(文档) | 类似数据库中的“行”,JSON格式数据 |
| Shard(分片) | 索引被分割成多个分片,分片可分布在不同节点上 |
| Replica(副本) | 分片的备份 |
| Mapping(映射) | 定义文档的字段及类型 |
1.2 MYSQL 和 ElasticSearch 对比
| MYSQL | Database(数据库) | Row(行) | Column(列) |
| ↓ | ↓ | ↓ | ↓ |
| ElasticSearch | Index(索引) | Document(文档) | Fileds(字段) |
1.3 ES 数据类型
| 数据类型 | ||
| 字符串 | text | 全文搜索(如文章内容、描述),支持分词、模糊匹配,不适合排序和聚合 |
| keyword | 精确匹配(如状态码、标签、ID),不分词,适合过滤、排序和聚合 | |
| 数值 | long / integer(整数) double / float(浮点数) | |
| 日期 | date | |
| 布尔 | boolean | true / false |
| 二进制 | binary | 存储Base64编码的二进制数据(如图片) |
| 对象 | object | JSON对象 |
| 嵌套 | nested | 对象数组 |
| 地理 | geo_point | 经纬度坐标 |
| geo_shape | 复杂地理形状(如多边形区域) | |
| 数组 | [ ] | 存储同类型多值 |
2. 下载
ElasticSearch:Download Elasticsearch | Elastic
Kibana可视化平台:Download Kibana Free | Get Started Now | Elastic
3. 启动
3.1 启动ElasticSearch
第一次启动会初始化一个密码,用户名:elastic。
如果忘记密码,使用命令重置密码:elasticsearch-reset-password -u elastic
注意要保存新密码


3.2 启动 Kibana(先修改配置文件,再启动)

4. 正排索引和倒排索引
4.1 正排索引(id 映射 内容)
| id | content |
| 100 | 华为 Mate 60 手机 |
| 101 | iPhone 16 手机 |
| 102 | 小米汽车 |
4.2 倒排索引(分词 映射 id)
| keyword | id |
| 手机 | 100,101 |
| 华为 | 100 |
| iPhone | 101 |
| 汽车 | 102 |
5. Index 索引(使用 PostMan 请求)
5.1 新增 goods 索引( PUT )

// number_of_shards: 定义了索引的主分片数量。数据会被分成几个分片(shard)
// number_of_replicas: 定义了每个主分片的副本数量。主分片的备份数
// mappings: 定义了索引中存储的文档的字段及其数据类型{"settings": {"number_of_shards": 1,"number_of_replicas": 1},"mappings": {"properties": {"goods_name": { "type": "text" },"price": { "type": "float" },"created_time": { "type": "date","format": "yyyy-MM-dd HH:mm:ss" }}}
}
5.2 查询 goods 索引( GET )

5.3 删除 goods 索引( DELETE )

6. Document 文档
6.1 新增 Document( POST _doc )


{"goods_name": "西瓜","price": 19.9,"created_time": "2025-03-24 21:00:00"
}
6.2 根据 id 查询 Document( GET _doc )

6.3 根据 id 局部更新 Document( POST _update )

验证局部更新

6.4 根据 id 删除 Document( DELETE _doc )

6.5 查询
6.5.1 查询 goods 所有 Document( GET _search )


6.5.2 条件查询 goods 的 Document 内容( GET _search )


{"query":{"match":{"goods_name": "香蕉"}},"_source": ["price"]
}
6.5.3 分页查询 goods 所有 Document 内容( GET _search )

6.5.4 排序查询 goods 所有 Document 内容( GET _search )( desc:降序,asc:升序 )

{"sort": {"price":{"order": "desc"}}
}
6.5.5 多条件查询 goods 所有 Document 内容( GET _search )


{"query":{"bool":{"must":[{ "match":{ "goods_name":"西瓜" } },{ "match":{ "price":19.9 } }]}}
}
6.5.6 范围查找 goods 所有 Document 内容( GET _search )


6.5.7 全文检索 && 精确匹配 && 高亮显示 ( GET _search )



6.5.8 聚合查询 ( GET _search )
(1)平局值(avg)

(2)求和(sum)

(3)最大值/最小值(max/min)

(4)统计汇总(stats)

7. 分词器
| Standard(单字分词) | standard | 中,华,人,民,共,和,国,国,歌 |
| IK(中文词库分词) | ik_smart(最少切分) | 中华人民共和国,国歌 |
| ik_max_word(最细粒度划分) | 中华人民共和国。中华人民,中华,华人,人民... |
7.1 下载 IK 中文分词器
Index of: analysis-ik/stable/

7.2 使用 IK 分词器


7.3 自定义分词 (词库没有“敖丙”,所以要自定义分词)





