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: 什么是 ...
随机推荐
- Hanoi-C
什么是汉诺塔?汉诺塔(Tower of Hanoi),又称河内塔,是一个源于印度古老传说的益智玩具.大梵天创造世界的时候做了三根金刚石柱子,在一根柱子上从下往上按照大小顺序摞着64片黄金圆盘.大梵天命 ...
- golang结构体判断是否为空
前言 使用任何编程语言都会遇到判空的问题,那么Golang对于自定义的结构体类型如何判空呢? 其实空结构体可不是简单的与nil做比较哦.请看下面两种方法: package main import ( ...
- 分享一个我遇到过的“量子力学”级别的BUG。
你好呀,我是歪歪. 前几天在网上冲浪的时候,看到知乎上的这个话题: 一瞬间,一次历史悠久但是记忆深刻的代码调试经历,"刷"的一下,就在我的脑海中蹦出来了. 虽然最终定位到的原因令人 ...
- git和github的入门操作
之前因为工作中用的都是SVN版本控制工具,没接触过git和github,现在开始深入自学Django框架技术后,看到官网推荐使用git,然后这两天网上查阅了很多文章教程,学到入门操作需要学习的点,太多 ...
- pandas(进阶操作)-- 政治献金项目数据分析
博客地址:https://www.cnblogs.com/zylyehuo/ 开发环境 anaconda 集成环境:集成好了数据分析和机器学习中所需要的全部环境 安装目录不可以有中文和特殊符号 jup ...
- StringBuilder案例
1.案例一 如图 这里无法使用反转方法的原因是,s属于String类型,而反转的方法存在于StringBuilder类型,所以我们要将s的类型转换为StringBuilder String--> ...
- MySqlDataAdapter.Fill() 报异常‘给定关键字不在字典中’的解决方案
MySqlDataAdapter.Fill() 报异常'给定关键字不在字典中'的解决方案 解决办法 升级依赖库 后来发现居然是MySql.Data.dll文件版本问题,我开始使用的是6.2.1.0版本 ...
- VJ结营测试
A 这题其实自己画一下图可以发现当奇数行为每行都为W,偶数行为W与R交替出现,就可以得到满足题意的图形了. 点击查看代码 #include<bits/stdc++.h> using nam ...
- Mybatis三大执行器
目录 1.执行器介绍 执行器的选择入口 设置执行器两种方式 全局配置(不建议) 局部设置(建议) 2.三个执行器区别 SimpleExecutor ReuseExecutor BatchExecuto ...
- CentOS linux 安装openssl(openssl拒绝服务漏洞【CVE-2022-0778】解决)
一.安装 1.下载相关openssl包 下载地址: https://www.openssl.org/source/ 2.将下载好的压缩包放到 /app/server/nginx 路径下(根据自己实际需 ...