elasticsearch中的分词器配置及使用
·
一、什么是分词器?
在 Elasticsearch(ES)中,分词器(Analyzer) 是处理文本的核心组件,负责将原始文本转换为可搜索的索引词(Term)。它是文本分析过程的核心,直接影响搜索的准确性和召回率。
简单来说,当你向 ES 索引一个文本字段时,分词器会对文本进行一系列处理,最终产出供 ES 存储和检索的「最小语义单元」(即 Term);而在搜索时,ES 会对查询文本使用相同的分词器处理,再去匹配索引中存储的 Term。
二、es中常见内置分词器
- standard: 默认分词器,按 Unicode 标准拆分,去除标点,转为小写(适合英文,对中文支持差,会拆成单字)。
- whitespace: 仅按空格拆分,不做其他处理(适合空格分隔的语言)。
- simple: 按非字母字符拆分,转为小写(适合简单英文场景)。
- keyword: 不做分词,将整个文本作为一个词元(适合精确匹配,如身份证号、手机号)。
三、自定义分词器
1、ngram分词器
释义: 在 Elasticsearch 中,ngram 分词器是一种基于滑动窗口原理的特殊分词器,它通过生成文本中连续的 n 个字符序列(ngram)来实现分词,非常适合处理模糊搜索、拼写纠错、自动补全(Autocomplete)等场景。
以下为自定义使用ngram分词器,min_gram:为分词的最少字数,max_gram:为分词的最大字数,依据该范围,将文本依照顺序,挨个进行分词。
分词配置示例:
{
"settings": {
"number_of_shards": 1,
"number_of_replicas": 0,
"index": {
"max_ngram_diff": 3
},
"analysis": {
"tokenizer": {
"ngram_tokenizer": {
"type": "ngram",
"min_gram": 2,
"max_gram": 5,
"token_chars": [
"letter",
"digit",
"punctuation"
]
}
},
"analyzer": {
"ngram_analyzer": {
"type": "custom",
"tokenizer": "ngram_tokenizer"
}
}
}
},
"mappings": {
"properties": {
"content": {
"type": "text",
"analyzer": "ngram_analyzer"
}
}
}
}
在创建索引时,需要显式的指定字段的分词器,如果不指定,就会使用默认分词器standard,standard分词器的索引占比ik差不多,ngram(2-5)占比为前者的3倍
2、ik分词器
释义: 在 Elasticsearch(ES)中,IK 分词器是一款专为中文文本设计的分词工具 **,解决了 ES 内置分词器对中文处理的局限性(如将中文拆分为单字),能根据语义和词典规则将中文文本拆分为合理的词语单元,大幅提升中文搜索的准确性和召回率。
分词器配置示例:
{
"settings": {
"number_of_shards": 12,
"number_of_replicas": 0,
"analysis": {
"analyzer": {
"ik": {
"tokenizer": "ik_max_word"
}
}
}
},
"mappings": {
"properties": {
"content": {
"type": "text",
"index": false
},
"createTime": {
"type": "date"
},
"dataId": {
"type": "keyword"
},
"gatherTopic": {
"type": "text",
"index": false
},
"matchText": {
"type": "text"
},
"matchTextIk": {
"type": "text",
"analyzer": "ik"
},
"mediaType": {
"type": "integer"
},
"publishTime": {
"type": "date"
}
}
}
}
3、查看文本分词情况
test/_analyze POST
{
"analyzer": "ngram_analyzer", #分词器
"text": "需要查看的文本"
}
4、自定义分词进行精准匹配查询
{
"settings": {
"number_of_replicas": "0",
"number_of_shards": "1",
"analysis": {
"analyzer": {
"comma_analyzer": {
"type": "pattern",
"pattern": ","
}
}
}
},
"mappings": {
"properties": {
"tags": {
"type": "text",
"analyzer": "comma_analyzer",
"store": true //单独存储
},
"id": {
"type": "integer"
},
"title": {
"type": "text"
}
}
}
}
以上为分词器的说明,以及在es中创建索引时,如何设置分词器,并且在字段中如何配置的指引。
感谢您的浏览!!!
更多推荐



所有评论(0)