elasticsearch match_phrase语句你真的理解了吗?
2015 年 4 月 21 日
这是我今天对于elasticsearch的一点体会,elasticsearch默认的分词器是standard,就是以空格进行分词,elasticsearch语句和standard分词器结合的比较好,在学习的过程中,测试英文没有问题,但一旦遇到中文或者中文分词,好像就不是那么顺利了,甚至很多参数对中文分词器没有用,所以理解中文分词器看来非常关键,今天我使用match_phrase语句进行简单的总结。
match_phrase是短语匹配,是为了更加精准的搜索,在某些场景下非常有用,仔细体会官方文档的介绍:
match_phrase是短语匹配,是为了更加精准的搜索,在某些场景下非常有用,仔细体会官方文档的介绍:
The match_phrase query analyzes the text and creates a phrase query out of the analyzed text.
standard分词器
先索引两条数据
POST testen/_doc/1 { "message": "i like footbool" } POST testen/_doc/2 { "message": "我们大家好中国人喜欢运动" }
进行搜索,没毛病,看上去很完美:
GET testen/_search { "query": { "match_phrase": { "message": { "query": "i like" } } } }
没有出现想要的结果,说明分词的顺序很重要(短语搜索和索引关系很大):
GET testen/_search { "query": { "match_phrase": { "message": { "query": "like i" } } } }
为了让短语匹配宽松一点,使用slop,没毛病:
GET testen/_search { "query": { "match_phrase": { "message": { "query": "i footbool", "slop": 1 } } } }
对中文看上去支持的不错,因为标准分词器将中文分为了一个个字符(缺点反而变为了优点):
GET testen/_search { "query": { "match_phrase": { "message": { "query": "我们大家运动", "slop": 6 } } } }
中文分词器
接下去我们看看中文分词,match_phrase是如何处理的:
PUT testcn { "mappings": { "properties": { "message": { "type": "text", "analyzer": "hanlp", "fields": { "keyword": { "type": "keyword" } } } } } }
先索引没有意义的一个句子:
POST testcn/_doc/1 { "message": "我们大家好中国人喜欢运动" }
看看分词过程:
GET /_analyze { "text": "我们大家好中国人喜欢运动", "analyzer": "hanlp" }
匹配到了:
GET testcn/_search { "query": { "match_phrase": { "message": { "query": "大家好中国人喜欢", "slop": 2 } } } }
这句更简单,居然没有匹配到:
GET testcn/_search { "query": { "match_phrase": { "message": { "query": "中国人喜欢", "slop": 2 } } } }
这说明什么?换句 比较通顺
的句子吧:
POST testcn/_doc/2 { "message": "今天我去了北京天安门" } GET testcn/_search { "query": { "match_phrase": { "message": { "query": "去了天安门", "slop": 1 } } } } GET testcn/_search { "query": { "match_phrase": { "message": { "query": "我天安门", "slop": 3 } } } }
结果看上去还行。
所以说,如果要使用短语匹配,用标准分词器是不是支持的也不错?用中文分词器反而不好?