文本检索是关系型数据库(如 MySQL)的弱项,而恰恰是 ES 的强项。前一篇文章已经提到了 match、term,除此之外还有multi_match、match_phrace 等,分别的含义是:
match
从一个字段中检索关键字,包括模糊检索、精准单词检索以及短语检索。
match_phrase
短语检索。跟 match 相似,也是从一个字段中检索文字,但是作为一个完整的短语检索,不能拆分成为几个单词来检索。
multi_match
从多个字段中检索关键字。其它与 match 相同。
match 的例子
GET /_search
{
"query": {
"match" : {
"message" : "this is a test"
}
}
}
多个字段可以写上多个 match,外面套上 must、must_not 或者 should。例如
GET /_search
{
"query": {
"bool": {
"should": [
{ "match" : { "title" : "this is a test" } },
{ "match" : { "content" : "this is a test" } }
]
}
}
}
multi_match 的例子
上面的例子用 multi_match 的写法
GET /_search
{
"query": {
"multi_match" : {
"query": "this is a test",
"fields": [ "title", "message" ],
"type": "most_fields"
}
}
}
如果省略 fields,表示将从全部字段中检索关键字。type 还有一种很常用的用法:best_fields,表示关键字都出现在同一个字段的文档将获得高的 _score。
match_phrace 的例子
match_phrace 和 match 的用法类似。不同的是,match_phrace 搜索的是完整的词组。例如搜索文字“编程语言”,match 将文字拆成两个单词“编程”和“语言”,匹配到的文档两个关键字不必连在一起。而 match_phrace 要求关键字连在一起,而且刚好就是“编程语言”。如果用 MySQL 来做类比,match 更像模糊匹配,而 match_phrace 就是精确匹配。