精确值查询 Term
term vs match
term:查询词不做分析,适用于如日期、bool、number、文本类型
match:查询词分析,并转化为term查询
下图查找结果为空,因为GOOD-NAME在索引时(这里索引是动词,代表插入文档)已经被分词器分词为两个词条good、name
可以设置字段为类型为keyword,这样在索引时不会分词,这样就能查询到了:
对于精确值查询尽量使用filter,filter不会评分且容易被缓存,所以filter的执行速度非常快,filter需要嵌套在bool或者constant_score中:
还有一个terms查询,相当于sql的in,文档和数组中任意一个数据值匹配即可:
{
"query":{
"terms":{
"name.keyword":["GOOD-NAME","BAD-NAME"]
}
}
}
Match查询
term查询类似sql,match则比term高级一些:
{
"query": {
"match": {
"likes":"dota basketball"
}
}
}
likes是文本类型(非keyword),搜索词也会被分析(dota、basketball),最终转化为term查询:
{
"query": {
"bool": {
"should":[
{"term":{"likes":"dota"}},
{"term":{"likes":"basketball"}}
]
}
}
}
若只想搜索出两个词都存在的文档:
{
"query": {
"match":{
"likes":{
"query":"dota basketball",
"operator":"and"
}
}
}
}
field之后不是直接跟关键词,而是一个json对象,operator默认是or,写成and和下面是等价的:
{
"query": {
"bool": {
"must":[
{"term":{"likes":"dota"}},
{"term":{"likes":"basketball"}}
]
}
}
}
上面的查询和下面的也是等价的
{
"query": {
"bool": {
"should":[
{"term":{"likes":"dota"}},
{"term":{"likes":"basketball"}}
],
"minim