可以使用以下接口查看各个分词器的分词效果。
GET _analyze
{
"analyzer": "分词器名称",
"text": "待分词的字符串"
}
ES的默认分词器,根据单词进行切分,并把切分后的单词转为小写,停词不会被过滤。
会把字符串中所有非字母的字符去掉,并按单词进行切分,停词不会被过滤。
根据空格进行切分。
在Simple分词器的基础上加入停词过滤功能。
不对结果进行分词。
根据正则表达式进行分词。
一个分词器包含以下几个组件:
对输入的文本进行预处理,然后把处理后的文本交给Tokenizer进行分词。
常见的Character Filter有:
对文本进行切分,输出字符数组,交给Token Filter。
常见的Tokenizer有:
对Tokenizer切分后的字符数组进一步处理。
常见的Token Filter有:
通过以下命令可以测试自定义分词器的效果:
GET _analyze
{
"tokenizer": "$tokenizer",
"char_filter": [$char_filter_array],
"filter": [$token_filter_array],
"text": "$text"
}
通过设置索引的settings可以创建总定义分词器,在下面的例子中我们分别配置了Tokenizer、Char Filter和Token Filter,并将他们组成一个新的自定义分词器my_custom_analyzer。
PUT test_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": "and"
}
}
}
}
}
通过以下语句可以测试自定义分词器的效果。
GET test_index/_analyze
{
"analyzer": "my_custom_analyzer",
"text": "I'm a :) person, and you?"
}
运行结果如下:
{
"tokens" : [
{
"token" : "i'm",
"start_offset" : 0,
"end_offset" : 3,
"type" : "word",
"position" : 0
},
{
"token" : "a",
"start_offset" : 4,
"end_offset" : 5,
"type" : "word",
"position" : 1
},
{
"token" : "happy",
"start_offset" : 6,
"end_offset" : 8,
"type" : "word",
"position" : 2
},
{
"token" : "person",
"start_offset" : 9,
"end_offset" : 15,
"type" : "word",
"position" : 3
},
{
"token" : "you",
"start_offset" : 21,
"end_offset" : 24,
"type" : "word",
"position" : 5
}
]
}
可以看到分词后“and”被去掉了,这是因为我们把停词设置成了“and”。