elasticsearch分词

阅读说明:

  1. 如果有排版格式问题,请移步www.yuque.com/mrhuang-ire... 《elasticsearch分词》,选择宽屏模式效果更佳。
  2. 本文为原创文章,转发请注明出处。

在建立倒排索引之前,先要分词器对文档数据进行处理。分析器是用于将文本数据划分为一系列的单词(或称之为词项、tokens)的组件。一个分析器包含以下三个部分:

  • 字符过滤器(Character filters)-使用字符过滤器转变字符,比如去除HTML标签,将数字转换为文字, 将特殊符号转换成文本等;
  • 分词器(Tokenizer)-将文本按照规则切分为单个或多个分词;
  • 分词过滤器(Token filters)-对分词进一步加工。比如转为小写,停滞词过滤等;

然后eleasticsearch搜索引擎Lucene对分词建立倒排索引,只有text类型才支持分词。 eleasticsearch内部自带了多个分析器,还可以自定义分析器。对于中文,有专业的第三方分析器比如IKAnalyzer等。

内置分析器

Standard Analyzer

默认分词器, 按Unicode文本分割算法拆分 , 转化为小写 , 支持中文(但是中文按照每个文字拆分,没啥意义)

示例

json 复制代码
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目录。

自定义配置示例

json 复制代码
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

遇到非字母就切分,并且转化为小写。

示例

json 复制代码
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_预定义。

示例

json 复制代码
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目录。

自定义配置示例

json 复制代码
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

特点:遇到空格的时候会进行分词 , 不会转小写。 示例:

json 复制代码
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+, 并且默认会转为小写。

示例

json 复制代码
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 包含停滞词的文件的路径。

自定义配置示例

json 复制代码
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

特点:不分词 直接将输入当做输出

示例

json 复制代码
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

实现了指纹识别算法。 对输入文本小写,规范化删掉扩展符,排序,去重,连接处理成单个分词。如果配置了停滞词列表,停滞词也将被删除。

示例

json 复制代码
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示例

json 复制代码
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示例

json 复制代码
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示例

json 复制代码
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示例

json 复制代码
GET _analyze
{
  "tokenizer" : "standard",
  "filter" : ["lowercase"],
  "text" : "THE Quick FoX JUMPs"
}

分词结果:[ the, quick, fox, jumps ]

Stop token filter示例

json 复制代码
GET /_analyze
{
  "tokenizer": "standard",
  "filter": [ "stop" ],
  "text": "a quick fox jumps over the lazy dog"
}

分词结果:[ quick, fox, jumps, over, lazy, dog ]

自定义分析器示例

下面有一个完整的自定义分析器示例,包含字符过滤器,分词器和分词过滤器。

json 复制代码
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 查询。

示例

json 复制代码
//创建索引
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" : {}
        }
    }
}

返回结果:

json 复制代码
{"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 复制代码
<?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].www.elastic.co/guide/en/el... [2].mp.weixin.qq.com/s?__biz=Mzg...

[3].zhuanlan.zhihu.com/p/580356194

[4].github.com/medcl/elast... [5].www.elastic.co/guide/en/el... [6].www.elastic.co/guide/en/el... [7].www.elastic.co/guide/en/el...

相关推荐
uhakadotcom3 分钟前
FinGPT:金融领域的开源语言模型框架
后端·面试·github
计算机学姐23 分钟前
基于Asp.net的教学管理系统
vue.js·windows·后端·sqlserver·c#·asp.net·visual studio
Asthenia041230 分钟前
TCP的阻塞控制算法:无控制随便发/固定窗口/慢启动+阻塞避免/快恢复/TCP Cubic/BBR
后端
AntBlack1 小时前
Python 打包笔记 : 你别说 ,PyStand 确实简单易上手
后端·python·创业
xiaozaq1 小时前
Spring Boot静态资源访问顺序
java·spring boot·后端
熬夜苦读学习1 小时前
库制作与原理
linux·数据库·后端
uhakadotcom2 小时前
Pandas入门:数据处理和分析的强大工具
后端·面试·github
Asthenia04122 小时前
Json里面想传图片(验证码图)-Base64编码来助你!
后端
服务端技术栈2 小时前
MySQL 索引:数据库查询的“加速器”
后端
Asthenia04123 小时前
Redis与MySQL协同:旁路缓存机制
后端