elasticsearch分词
阅读说明:
1.如果有排版格式问题,请移步https://www.yuque.com/mrhuang-ire4d/oufb8x/gmzl30v8ofqg3ua3?singleDoc# 《elasticsearch分词》,选择宽屏模式效果更佳。
2.本文为原创文章,转发请注明出处。
在建立倒排索引之前,先要分词器对文档数据进行处理。分析器是用于将文本数据划分为一系列的单词(或称之为词项、tokens)的组件。一个分析器包含以下三个部分:
- 字符过滤器(Character filters)-使用字符过滤器转变字符,比如去除HTML标签,将数字转换为文字, 将特殊符号转换成文本等;
- 分词器(Tokenizer)-将文本按照规则切分为单个或多个分词;
- 分词过滤器(Token filters)-对分词进一步加工。比如转为小写,停滞词过滤等;
然后eleasticsearch搜索引擎Lucene对分词建立倒排索引,只有text类型才支持分词。

eleasticsearch内部自带了多个分析器,还可以自定义分析器。对于中文,有专业的第三方分析器比如IKAnalyzer等。
通常,搜索和索引共用分析器,以确保查询中的分词与反向索引中的分词具有相同的格式。也支持索引和查询使用不同的分析器满足个性化要求。
● analyzer:索引分析器,包含停用词参数。分词中包含停用词;
● search_analyzer: 指定非短语查询分词器,分词中删除停用词;
● search_quote_analyzer: 指定短语查询分词器,分词中包含停用词;
内置分析器
Standard Analyzer
默认分词器, 按Unicode文本分割算法拆分 , 转化为小写 , 支持中文(但是中文按照每个文字拆分,没啥意义)
示例
POST _analyze
{
"analyzer": "standard",
"text": "The 2 QUICK Brown-Foxes jumped over the lazy dog's bone."
}
分词结果:[ the, 2, quick, brown, foxes, jumped, over, the, lazy, dog's, bone ]
Standard Analyzer配置
| 参数 | 说明 |
|---|---|
| max_token_length | 分词最大长度,默认255。 |
| stopwords | 自定义停滞词。例如_english_,或一个停滞词数组, 默认_english_。 |
| stopwords_path | 包含停滞词的文件的路径,路径相对于Elasticsearch的config目录。 |
自定义配置示例
PUT my_index
{
"settings": {
"analysis": {
"analyzer": {
"my_english_analyzer": {
"type": "standard",
"max_token_length": 5,
"stopwords": "_english_"
}
}
}
}
}
POST my_index/_analyze
{
"analyzer": "my_english_analyzer",
"text": "The 2 QUICK Brown-Foxes jumped over the lazy dog's bone."
}
分词结果:[ 2, quick, brown, foxes, jumpe, d, over, lazy, dog's, bone ]
Simple Analyzer
遇到非字母就切分,并且转化为小写。
示例
POST _analyze
{
"analyzer": "simple",
"text": "The 2 QUICK Brown-Foxes jumped over the lazy dog's bone."
}
分词结果:[ the, quick, brown, foxes, jumped, over, the, lazy, dog, s, bone ]
Stop Analyzer
在simple的基础上, 删除停滞词(停止词是指常见而无意义的词汇比如a, an, and, are, as, at, be, but, by, for, if, in, into, is, it, no, not, of, on, or, such, that, the, their, then, there, these, they, this, to, was, will, with),默认使用 stop token filter 的_english_预定义。
示例
POST _analyze
{
"analyzer": "stop",
"text": "The 2 QUICK Brown-Foxes jumped over the lazy dog's bone."
}
分词结果:[ quick, brown, foxes, jumped, over, lazy, dog, s, bone ]
Stop Analyzer 配置
| 参数 | 说明 |
|---|---|
| stopwords | 自定义停滞词。例如_english_,或一个停滞词数组, 默认_english_。 |
| stopwords_path | 包含停滞词的文件的路径,路径相对于Elasticsearch的config目录。 |
自定义配置示例
PUT my_index
{
"settings": {
"analysis": {
"analyzer": {
"my_stop_analyzer": {
"type": "stop",
"stopwords": ["the", "over"]
}
}
}
}
}
POST my_index/_analyze
{
"analyzer": "my_stop_analyzer",
"text": "The 2 QUICK Brown-Foxes jumped over the lazy dog's bone."
}
分词结果:[ quick, brown, foxes, jumped, lazy, dog, s, bone ]
Whitespace Analyzer
特点:遇到空格的时候会进行分词 , 不会转小写。
示例:
POST _analyze
{
"analyzer": "whitespace",
"text": "The 2 QUICK Brown-Foxes jumped over the lazy dog's bone."
}
分词结果:[ The, 2, QUICK, Brown-Foxes, jumped, over, the, lazy, dog's, bone. ]
Patter Analyzer
按照正则表示式去切分,默认为\W+, 并且默认会转为小写。
示例
POST _analyze
{
"analyzer": "pattern",
"text": "The 2 QUICK Brown-Foxes jumped over the lazy dog's bone."
}
分词结果:[ the, 2, quick, brown, foxes, jumped, over, the, lazy, dog, s, bone ]
Patter Analyzer配置
| 参数 | 说明 |
|---|---|
| pattern | 正则表达式,默认\W+。 |
| flags | Java正则表达式flags,多个用|分离,例如"CASE_INSENSITIVE | COMMENTS"。 |
| lowercase | 是否小写。默认true。 |
| stopwords | 预定义停滞词列表,例如_english_, 或一个停滞词数组,默认_none_。 |
| stopwords_path | 包含停滞词的文件的路径。 |
自定义配置示例
PUT my_index
{
"settings": {
"analysis": {
"analyzer": {
"my_email_analyzer": {
"type": "pattern",
"pattern": "\\W|_",
"lowercase": true
}
}
}
}
}
POST my_index/_analyze
{
"analyzer": "my_email_analyzer",
"text": "John_Smith@foo-bar.com"
}
分词结果:[ john, smith, foo, bar, com ]
Keyword Analyzer
特点:不分词 直接将输入当做输出
示例
POST _analyze
{
"analyzer": "keyword",
"text": "The 2 QUICK Brown-Foxes jumped over the lazy dog's bone."
}
分词结果:[ The 2 QUICK Brown-Foxes jumped over the lazy dog's bone. ]
Fingerprint Analyzer
实现了指纹识别算法。
对输入文本小写,规范化删掉扩展符,排序,去重,连接处理成单个分词。如果配置了停滞词列表,停滞词也将被删除。
示例
POST _analyze
{
"analyzer": "fingerprint",
"text": "Yes yes, Gödel said this sentence is consistent and."
}
分词结果:[ and consistent godel is said sentence this yes ]
Language Analyzers
针对特殊语言专门的分词器。这里不做详细介绍,后面有针对中文讲解中文分词器。
自定义分析器
当内置分析器不能满足您的需求时,您可以创建一个自定义分析器。一个自定义分词器由零个或多个char filters, 一个 Tokenizer 和零个或多个 token filters 组成。elasticsearch已经内置了多个字符过滤器,分词器和分词过滤器。
字符过滤器(Character Filters)
- HTML Strip Character Filter: 从输入文本中移除HTML元素。比如
Hello World
被处理为 Hello World,简写为html_strip。
- Mapping Character Filter:通过一个预定义的映射关系,将指定的字符或字符串替换为其他字符或字符串。例如,你可以定义一个规则将 "&" 替换为 "and"。简写为mapping.
- Pattern Replace Character Filter:使用正则表达式匹配和替换字符, 简写为pattern_replace。
HTML Strip Character Filter示例
GET /_analyze
{
"tokenizer": "keyword",
"char_filter": [
"html_strip"
],
"text": "<p>I'm so <b>happy</b>!</p>"
}
分词结果:[ \nI'm so happy!\n ]
Mapping Character Filter示例
GET /_analyze
{
"tokenizer": "keyword",
"char_filter": [
{
"type": "mapping",
"mappings": [
"٠ => 0",
"١ => 1",
"٢ => 2",
"٣ => 3",
"٤ => 4",
"٥ => 5",
"٦ => 6",
"٧ => 7",
"٨ => 8",
"٩ => 9"
]
}
],
"text": "My license plate is ٢٥٠١٥"
}
分词结果:[ My license plate is 25015 ]
Pattern Replace Character Filte示例
GET /_analyze
{
"tokenizer": "keyword",
"char_filter": [
{
"type": "pattern_replace",
"pattern": "(\\d+)-(?=\\d)",
"replacement": "$1_"
}
],
"text": "My credit card is 123-456-789"
}
分词结果:[My credit card is 123_456_789]
分词器(Tokenizer)
在内置分词器部分已经详细讲过了。
分词过滤器(Token Filters)
系统已经提供了多个分词过滤器,完整请参考Token filter reference | Elasticsearch Guide [7.7] | Elastic。
- Lowercase token filter: 转换为小写,简称为lowercase.
- Stop token filter:移除停顿词,简称为stop.
Lowercase token filter示例
GET _analyze
{
"tokenizer" : "standard",
"filter" : ["lowercase"],
"text" : "THE Quick FoX JUMPs"
}
分词结果:[ the, quick, fox, jumps ]
Stop token filter示例
GET /_analyze
{
"tokenizer": "standard",
"filter": [ "stop" ],
"text": "a quick fox jumps over the lazy dog"
}
分词结果:[ quick, fox, jumps, over, lazy, dog ]
自定义分析器示例
下面有一个完整的自定义分析器示例,包含字符过滤器,分词器和分词过滤器。
PUT my_index
{
"settings": {
"analysis": {
"analyzer": {
"my_custom_analyzer": {
"type": "custom",
"char_filter": [
"emoticons"
],
"tokenizer": "punctuation",
"filter": [
"lowercase",
"english_stop"
]
}
},
"tokenizer": {
"punctuation": {
"type": "pattern",
"pattern": "[ .,!?]"
}
},
"char_filter": {
"emoticons": {
"type": "mapping",
"mappings": [
":) => _happy_",
":( => _sad_"
]
}
},
"filter": {
"english_stop": {
"type": "stop",
"stopwords": "_english_"
}
}
}
}
}
POST my_index/_analyze
{
"analyzer": "my_custom_analyzer",
"text": "I'm a :) person, and you?"
}
分词结果:[ i'm, _happy_, person, you ]
中文分词器 IKAnalyzer
IKAnalyzer提供两种分词:
ik_max_word: 会将文本做最细粒度的拆分,比如会将“中华人民共和国国歌”拆分为“中华人民共和国,中华人民,中华,华人,人民共和国,人民,人,民,共和国,共和,和,国国,国歌”,会穷尽各种可能的组合,适合 Term Query;
ik_smart: 会做最粗粒度的拆分,比如会将“中华人民共和国国歌”拆分为“中华人民共和国,国歌”,适合 Phrase 查询。
示例
//创建索引
XPUT /index
//映射配置
POST /index/_mapping -H 'Content-Type:application/json' -d'
{
"properties": {
"content": {
"type": "text",
"analyzer": "ik_max_word",
"search_analyzer": "ik_smart"
}
}
}
//写入数据
POST /index/_create/1
{"content":"美国留给伊拉克的是个烂摊子吗"}
POST /index/_create/2
{"content":"公安部:各地校车将享最高路权"}
POST /index/_create/2
{"content":"中韩渔警冲突调查:韩警平均每天扣1艘中国渔船"}
POST /index/_create/2
{"content":"中国驻洛杉矶领事馆遭亚裔男子枪击 嫌犯已自首"}
//查询含有中国的数据
POST /index/_search
{
"query" : { "match" : { "content" : "中国" }},
"highlight" : {
"pre_tags" : ["<tag1>", "<tag2>"],
"post_tags" : ["</tag1>", "</tag2>"],
"fields" : {
"content" : {}
}
}
}
返回结果:
{"took":14,"timed_out":false,"_shards":{"total":5,"successful":5,"failed":0},"hits":{"total":2,"max_score":2,"hits":[{"_index":"index","_type":"fulltext","_id":"4","_score":2,"_source":{"content":"中国驻洛杉矶领事馆遭亚裔男子枪击 嫌犯已自首"},"highlight":{"content":["<tag1>中国</tag1>驻洛杉矶领事馆遭亚裔男子枪击 嫌犯已自首 "]}},{"_index":"index","_type":"fulltext","_id":"3","_score":2,"_source":{"content":"中韩渔警冲突调查:韩警平均每天扣1艘中国渔船"},"highlight":{"content":["均每天扣1艘<tag1>中国</tag1>渔船 "]}}]}}
词库配置
IKAnalyzer已经内置了词库,在目录{ik_path}/config下。
- main.dic:主词库。
- stopword.dic:英文停用词,不会建立在倒排索引中。
- quantifier.dic:特殊词库:计量单位等。
- suffix.dic:特殊词库:行政单位。
- surname.dic:特殊词库:百家姓。
- preposition:特殊词库:语气词。
当然,也支持用户自定义词库,在{ik_path}/config目录下添加自定义词库文件,要求每行一个词并且UTF8 编码,然后修改文件{ik_path}/config/IKAnalyzer.cfg.xml, 添加自定义词库位置,重启es。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<comment>IK Analyzer 扩展配置</comment>
<!--用户可以在这里配置自己的扩展字典 -->
<entry key="ext_dict"></entry>
<!--用户可以在这里配置自己的扩展停止词字典-->
<entry key="ext_stopwords"></entry>
<!--用户可以在这里配置远程扩展字典 -->
<!-- <entry key="remote_ext_dict">words_location</entry> -->
<!--用户可以在这里配置远程扩展停止词字典-->
<!-- <entry key="remote_ext_stopwords">words_location</entry> -->
</properties>
参考:
[1].https://www.elastic.co/guide/en/elasticsearch/reference/7.7/analysis-analyzers.html
[2].https://mp.weixin.qq.com/s?__biz=Mzg4Nzc3NjkzOA==&mid=2247485544&idx=1&sn=cfa20adbb5c7328ea0cab85966d95c02&chksm=cf847badf8f3f2bbefd1b9e893cccf10a24c2a83f8052b613c62c999566e4c8616fded236552#rd
[3].https://zhuanlan.zhihu.com/p/580356194
[4].https://github.com/medcl/elasticsearch-analysis-ik
[5].https://www.elastic.co/guide/en/elasticsearch/reference/7.7/analysis-charfilters.html
[6].https://www.elastic.co/guide/en/elasticsearch/reference/7.7/analysis-tokenizers.html
[7].https://www.elastic.co/guide/en/elasticsearch/reference/7.7/analysis-tokenfilters.html
elasticsearch分词的更多相关文章
- Elasticsearch——分词器对String的作用
更多内容参考:Elasticsearch学习总结 关于String类型--分词与不分词 在Elasticsearch中String是最基本的数据类型,如果不是数字或者标准格式的日期等这种很明显的类型, ...
- elasticsearch分词插件的安装
IK简介 IK Analyzer是一个开源的,基于java语言开发的轻量级的中文分词工具包.从2006年12月推出1.0版开始, IKAnalyzer已经推出了4个大版本.最初,它是以开源项目Luen ...
- elasticsearch分词器Jcseg安装手册
Jcseg是什么? Jcseg是基于mmseg算法的一个轻量级中文分词器,同时集成了关键字提取,关键短语提取,关键句子提取和文章自动摘要等功能,并且提供了一个基于Jetty的web服务器,方便各大语言 ...
- Elasticsearch 分词器
无论是内置的分析器(analyzer),还是自定义的分析器(analyzer),都由三种构件块组成的:character filters , tokenizers , token filters. 内 ...
- elasticsearch分词器ik
1. 下载和es配套的版本 git clone https://github.com/medcl/elasticsearch-analysis-ik 2. 编译 cd elasticsearch-an ...
- Elasticsearch分词导致的查找错误
这周在做视频搜索的过程中遇到一个问题,就是用下面的查询表达式去Elasticsearch检索,检索不到想要的结果.查询语句如下: 而查询的字段的值为: "mergeVideoName&quo ...
- ElasticSearch分词器
什么是分词器? 分词器,是将用户输入的一段文本,分析成符合逻辑的一种工具.到目前为止呢,分词器没有办法做到完全的符合人们的要求.和我们有关的分词器有英文的和中文的.英文的分词器过程:输入文本-关键词切 ...
- ElasticSearch——分词
前言: 最近在使用elasticSearch中发现有些数据查不出来,于是研究了一下,发现是分词导致的,现梳理并总结一下. ElasticSearch 5.0以后,string类型有重大变更,移除了st ...
- 掌握 analyze API,一举搞定 Elasticsearch 分词难题
初次接触 Elasticsearch 的同学经常会遇到分词相关的难题,比如如下这些场景: 为什么明明有包含搜索关键词的文档,但结果里面就没有相关文档呢? 我存进去的文档到底被分成哪些词(term)了? ...
- ElasticSearch 分词器,了解一下
这篇文章主要来介绍下什么是 Analysis ,什么是分词器,以及 ElasticSearch 自带的分词器是怎么工作的,最后会介绍下中文分词是怎么做的. 首先来说下什么是 Analysis: 什么是 ...
随机推荐
- linux ssh 免密登录
1.服务器端开启密钥登录模式 $ vim /etc/ssh/sshd_config # 是否允许 root 远程登录 PermitRootLogin yes # 密码登录是否打开 PasswordAu ...
- VS 2022 WEB发布编译失败
VS2022当安装在非默认路径时,每次更新后,在发布时,就会出来编译失败的提示,比如这样: C:\VS2022\Preview\MSBuild\Microsoft\VisualStudio\v17.0 ...
- SpringBoot + 布隆过滤器:亿级数据下的高效防护盾与缓存穿透实战指南
在当今高并发.海量数据的应用场景中,布隆过滤器凭借其极低的内存占用和极快的查询效率,成为解决缓存穿透.数据预判等难题的利器.本文深度解析布隆过滤器的核心原理与实战应用,手把手教你如何将这一数据守门员融 ...
- OpenAI的GPT-4o:普通人的AI秘书来了
1. 惊艳时刻:AI比你想象的更"人性" 早餐时,张三正埋头刷推送,一篇关于OpenAI发布GPT-4o的文章瞬间点燃了他的好奇心.这个AI简直是科技圈的惊雷!竟然可以像真人一样说 ...
- 牛客小白月赛104 C-小红打怪
小红打怪 答案有单调性,使用二分答案来做 但是当时没有想到用二分,而是卡在怎么处理这三种攻击了. 可以把进行x回合的攻击,分为先进行x回合的全体打击,再进行x回合的范围打击,最后验证剩余血量够不够x回 ...
- 智能驾驶致死、AI聊天自杀,安全成最大的奢侈
提供AI咨询+AI项目陪跑服务,有需要回复1 前几天<高层论坛:实现汽车产业高质量发展>才刚召开,因为汽车行业卷得不行,现在大家都想在智能驾驶上发力,其中有句话令我影响深刻: 对智能驾驶来 ...
- python之random函数,随机取值
如 a =['辣椒炒肉','红烧肉','剁椒鱼头','酸辣土豆丝','芹菜香干'] 需要从a数组中随机取出一个值打印出来 具体脚本 import random a =['辣椒炒肉','红烧肉','剁椒 ...
- Yuque Rich Text(语雀富文本编辑器)
Yuque Rich Text(语雀富文本编辑器) 由于本人觉得语雀编辑器非常好用,很符合我的使用习惯,然后发现语雀的Chrome浏览器插件实现了编辑器的功能,所以将其富文本的功能拆分位一个单独的Vu ...
- Python3批量爬取美女照片并保存到本地(二)
Python3批量爬取美女照片并保存到本地(二) 上一波写错了,很尴尬,就能爬显示的一部分照片,网站有限制,从上波的爬取可以看出来,返回的json中只有一部分图片,其余的需要登录才能下载,我们这次通过 ...
- uv全功能更新:统一管理Python项目、工具、脚本和环境的终极解决方案
花下猫语:uv 项目自发布起就大受欢迎,目前 Github star 52.6 K,远超过它的同类竞品们.前不久,它的创始人在 X 上披露了一组惊人的数据:uv 曾占据了 PyPI 超过 20% 的流 ...