match查询
match查询:全文搜索是其主要应用场景。会有相关度的计算。
单词查询
GET /my_index/my_type/_search
{
"query": {
"match": {
"title": "QUICK!"
}
}
}
多词查询
任何文档只要被查询字段里面包含 指定词项中的至少一个词 就可以被匹配,匹配的词项越多,文档越相关。
GET /my_index/my_type/_search
{
"query": {
"match": {
"title": "BROWN DOG!"
}
}
}
提高查询精度
match还可以通过operator操作符作为入参,默认情况为OR。 and会让所有指定词项都必须匹配。
GET /my_index/my_type/_search
{
"query": {
"match": {
"title": {
"query": "BROWN DOG!",
"operator": "and"
}
}
}
}
精度控制
minimum_should_match最小匹配参数,通常使用百分数指定搜索精度范围。可以应用很多不同的规则。
GET /my_index/my_type/_search
{
"query": {
"match": {
"title": {
"query": "quick brown dog",
"minimum_should_match": "75%"
}
}
}
}
组合查询
与term不同的是,match的bool过滤器的查询更加精妙,它会计算文档的相关程度
GET /my_index/my_type/_search
{
"query": {
"bool": {
"must": { "match": { "title": "quick" }},
"must_not": { "match": { "title": "lazy" }},
"should": [
{ "match": { "title": "brown" }},
{ "match": { "title": "dog" }}
]
}
}
}
返回结果
{
"hits": [
{
"_id": "3",
"_score": 0.70134366,
"_source": {
"title": "The quick brown fox jumps over the quick dog"
}
},
{
"_id": "1",
"_score": 0.3312608,
"_source": {
"title": "The quick brown fox"
}
}
]
}
bool查询会为每个文档计算相关度评分_score,再将所有匹配的must和should语句的分数_score求和, 最后除以 must 和 should 语句的总数。
控制match精度
没有must语句的时候,只有要有一个should语句匹配。
GET /my_index/my_type/_search
{
"query": {
"bool": {
"should": [
{ "match": { "title": "brown" }},
{ "match": { "title": "fox" }},
{ "match": { "title": "dog" }}
],
"minimum_should_match": 2 //既可以是数字,也可以是百分比
}
}
}
term和match的等价查询
match默认使用的是or操作符,而term查询中只有多个should语句的情况下,至少要求匹配一条语句。所以一下两条语句是等价的。
{
"match":{"title":"brown fox"}
}
等价于
{
"bool":{
"should":[
{"term":{"title":"brown"}},
{"term":{"title":"fox"}}
]
}
}
如果在使用match语句的过程中选择and操作符,在term查询中则需要使用must语句,一下两条语句是等价的。
{
"match":{
"title":{
"query":"brown fox",
"operator":"and"
}
}
}
等价于
{
"bool":{
"must":[
{"term":{"title":"brown"}},
{"term":{"title":"fox"}}
]
}
}
boost指定查询权重
GET /_search
{
"query": {
"bool": {
"must": {
"match": { //默认boost值为1
"content": {
"query": "full text search",
"operator": "and"
}
}
},
"should": [
{ "match": {
"content": {
"query": "Elasticsearch",
"boost": 3
}
}},
{ "match": {
"content": {
"query": "Lucene",
"boost": 2 //权重比Elasticsearch权重低一点
}
}}
]
}
}
}
boost权重的提升并不是线性的。