目录
app 原有的搜索功能无法进行拼音搜索,产品希望可以支持,例如内容中含有:中国通史记,那不管搜 `通史` or `tongshi`,都可以搜到这个内容
6.4.0
确定es目前是否支持pinyin的搜索能力,没有的话需要下载相关组件,下载这里不做介绍
可执行以下命令确定:
- POST /_analyze
- {
- "analyzer": "pinyin",
- "text": "中国通史"
- }
正常得到以下结果:
- {
- "tokens": [
- {
- "token": "zhong",
- "start_offset": 0,
- "end_offset": 0,
- "type": "word",
- "position": 0
- },
- {
- "token": "zgts",
- "start_offset": 0,
- "end_offset": 0,
- "type": "word",
- "position": 0
- },
- {
- "token": "guo",
- "start_offset": 0,
- "end_offset": 0,
- "type": "word",
- "position": 1
- },
- {
- "token": "tong",
- "start_offset": 0,
- "end_offset": 0,
- "type": "word",
- "position": 2
- },
- {
- "token": "shi",
- "start_offset": 0,
- "end_offset": 0,
- "type": "word",
- "position": 3
- }
- ]
- }
新增索引字段,例如:content_pinyin, analyzer为:pinyin
- PUT /index/_mapping/_doc
- {
- "properties": {
- "content_pinyin": {
- "type": "text",
- "analyzer": "pinyin"
- }
- }
- }
同步数据,将原content的文档数据同步给content_pinyin, 同步方式可参考 (生产环境要考虑数据量的问题,否则影响线上业务,数据过大建议使用脚本进行数据刷新):
- POST /index/_update_by_query
- {
- "script": {
- "source": "ctx._source.content_pinyin = ctx._source.content",
- "lang": "painless"
- },
- "query": {
- "match_all": {}
- }
- }
使用新字段进行搜索,结果如下:

搜索结果没有问题,但是会发现,高亮字段竟然是整个内容:

参考此文章:【精选】ElasticSearch7.6.2 拼音,中文,中音搜索,高亮搜索关键字_es 中文和拼音搜索-CSDN博客
找到了答案
需要修改索引设置,新增自定义分析器和过滤器来实现高亮
- # 要先临时关闭索引
- POST /index/_close
-
- # 修改索引设置
- PUT /index/_settings
- {
- "settings": {
- "analysis": {
- "analyzer": {
- "ik_pinyin_analyzer": {
- "tokenizer": "my_pinyin"
- }
- },
- "tokenizer": {
- "my_pinyin": {
- "type": "pinyin",
- "keep_full_pinyin": true,
- "keep_original": false,
- "limit_first_letter_length": 10,
- "lowercase": true,
- "remove_duplicated_term": false,
- "ignore_pinyin_offset": false,
- "keep_first_letter": true,
- "keep_separate_first_letter": true
- }
- }
- }
- }
- }
-
- # 打开索引
- POST /bm_ebook/_open
这里如果在线上操作,可能会导致一段时间的服务不可用,顺利的话大概五秒左右,如果能接受可以直接执行,不行的话只能新建索引,然后刷一遍数据
新建字段 (因为es不允许修改已经生效的字段的分析器,所以我只能再新建一个字段)
- PUT /index/_mapping/_doc
- {
- "properties": {
- "ik_content_pinyin": {
- "type": "text",
- "analyzer": "ik_pinyin_analyzer"
- }
- }
- }
这里分析器使用刚刚新增的自定义分析器: ik_pinyin_analyzer
然后同第三步,同步一下数据内容
通过新字段来进行拼音搜索,结果如下:
