这篇文章我们介绍下elasticsearch中的短语搜索,即:match_phrase查询。这个搜索其实一般主要会在英语中使用到。下面我们以一个案例来解释下。
例如现在有在elasticsearch中,我们需要存储以下信息
description = Whatever is worth doing is worth doing well description = Aah!What are you doing?
如果我们把name字段设置为keyword类型的话,那么就不会对这个语句进行分词,那么此时我们搜索 doing well的时候就不会被搜索到。
如果我们把name字段设置为text类型的话,那么elasticsearch就会对上面的语句进行分词,此时我们搜索doing well的时候,两条记录都会被搜索到。(因为在英文里面,所有的语句都是通过空格分词,此时查询的时候doing well也会被分词成doing 和 well,所以第二条记录会被查询到)
下面来演示一下
一、使用keyword类型进行演示
1)把description设置为keyword
put /test { "mappings": { "properties": { "description": { "type": "keyword" } } }, "settings": { "index": { "number_of_shards": "1", "number_of_replicas": "0" } } }
2)插入数据
post /test/_doc/1 {"description":"Whatever is worth doing is worth doing well"} post /test/_doc/2 {"description":"Aah!What are you doing?"}
3)搜索下doing well
可以看到使用term或者match都搜索不到想要的结果。
二、使用text类型进行演示
1)把type做成text
{ "mappings": { "properties": { "description": { "type": "text" } } }, "settings": { "index": { "number_of_shards": "1", "number_of_replicas": "0" } } }
2)插入数据
post /test/_doc/1 {"description":"Whatever is worth doing is worth doing well"} post /test/_doc/2 {"description":"Aah!What are you doing?"}
3)查询搜索下doing well
post /test/_search { "query": { "match": { "description": "doing well" } } }
可以看到两条记录都被搜索出来了。
但是试想一下,第二条命名就不是我们想要的,我们不期望使用这种结果,那么我们有没有办法不要第二条记录呢?这里就要用到我们这批文章介绍的短语搜索:match_phrase查询
下面我们试试这个短语搜索
post /test/_search { "query": { "match_phrase": { "description": "doing well" } } }
这时候我们就能匹配上了,不满足我们需要的信息也不会被查询出来。
还没有评论,来说两句吧...