Es 拼音搜索无法高亮

 

目录

背景:

Es 版本:

第一步

第二步 (错误步骤 - 只是记录过程)

第三步

第四步

第五步

第六步

第七步


背景:

app 原有的搜索功能无法进行拼音搜索,产品希望可以支持,例如内容中含有:中国通史记,那不管搜 `通史` or `tongshi`,都可以搜到这个内容

Es 版本:

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 中文和拼音搜索-优快云博客

找到了答案

需要修改索引设置,新增自定义分析器和过滤器来实现高亮

# 要先临时关闭索引
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

然后同第三步,同步一下数据内容

第七步

通过新字段来进行拼音搜索,结果如下:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值