所谓组合查询就是将单个查询条件通过某种逻辑关系组合起来查询,在实际项目中更多的以组合查询的方式使用
1.查询上下文
- filter: 只查询结果,没有相关性评分(性能更高,推荐使用)
- 查询语句中包含 filter
- query: 查询结果,并计算相关性得分(对匹配精度有要求的场景)
- 查询语句中不包含 filter
2.bool表达式查询(最主要的组合查询方式)
各组合语句是平行的关系,如:
POST steam_item_730/_search
{
"query": {
"bool" : {
//app_id = 730
"must" : {
"term" : { "app_id" : 730 }
},
//extra_tag_ids = "热销"
"filter": {
"term" : { "extra_tag_ids" : "热销" }
},
// price 不能在 [0.1,1]这个区间
"must_not" : {
"range" : {
"price" : { "gte" : 0.1, "lte" : 1 }
}
},
//name 中有 "久经" 或 short_name有 "久经"
"should" : [
{ "match" : { "name" : "久经" } },
{ "match" : { "short_name" : "久经" } }
],
// should 语句至少有一个成立
"minimum_should_match" : 1,
"boost" : 1.0
}
}
}
- 各bool表达式,之间是平行关系
- 各bool表达式的子句,可以是对象,也可以是一个数组(多个条件时)
- 各bool表达式的子句,使用单个搜索条件
(1)filter
- 功能:不需要计算相关性得分的过滤查询
- 实例
GET purchase_order/_doc/_search
{
"track_total_hits": true,
"query": {
"bool": {
"filter": [
{
"term": {
"order_status": 1
}
},
{
"terms": {
"pay_status": [
2,
20
]
}
}
]
}
}
}
上例查询 order_status = 1 而且 pay_status 在[2,20]这个范围内
(2)must
- 功能:所有条件都必须满足(类似于and,各子句是and关系)
- 实例:
GET purchase_order/_doc/_search
{
"track_total_hits": true,
"query": {
"bool": {
"must": [
{
"term": {
"order_status": 1
}
},
{
"terms": {
"pay_status": [
2,
20
]
}
}
]
}
}
}
和filter很类似,不过他会计算相关性得分,建议使用filter
(3)must_not
- 功能:所有条件都不满足(类似于not)
- 实例:
GET merchant_order/_doc/_search
{
"track_total_hits": true,
"query": {
"bool": {
"must_not": [
{
"exists": {
"field": "user_id"
}
}
]
}
}
}
上例作用是:查询卖家订单索引中不存在user_id这个字段的数据列表
(4)should
- 功能:满足其中指定数量的条件即可(类似于or)
- 注:一般它和minimum_should_match 一起使用,即至少满足指定的数量
GET merchant_order/_doc/_search
{
"track_total_hits": true,
"query": {
"bool": {
"should": [
{
"term": {
"attribute.type": "csgo_type_sticker"
}
},
{
"exists": {
"field": "attribute.sticker_capsule"
}
}
]
},
"minimum_should_match" : 1,
}
}
上例中的作用:查询 attribute.type=csgo_type_sticker或者 存在字段attribute.sticker_capsule 的数据
3.constant_score
- 功能: 相关性得分指定为一个常量
- 参数:
- filter : 查询条件
- boost: 相关性得分常量值(如果不指定默认为1)
- 实例:
GET steam_item_730/_doc/_search
{
"query":{
"constant_score":{
"filter":{
"match":{
"name":"运动手套"
}
},
"boost":1.2
}
}
}
查询出所有的文档相关性得分_score都是1.2
4.function_score
- 功能: 自定义相关性得分
- 参数:
- query: 查询条件
- boost: 相关性得分
- functions: 相关性得分函数
- filter: 查询条件
- 函数类型: random_score/script_score/weight
- script_score: 通过脚本计算得分
- min_boost: 最低得分
- max_boost: 最高得分
- boost_mode : 相关性得分模式
- multiply: 得分相背心
- score_mode: 计分模式(和boost_mode的选项值是一样的)
- 实例:
GET steam_item_730/_search
{
"query": {
"function_score": {
"query": { "match_all": {} },
"boost": "5",
"functions": [
{
"filter": { "term": { "attribute.type": "csgo_type_knife" } },
"weight": 15
},
{
"filter": { "term": { "attribute.type": "type_hands" } },
"weight": 10
}
],
"max_boost": 42,
"score_mode": "max",
"boost_mode": "multiply",
"min_score": 5
}
}
}
如:attribute.type = csgo_type_knife,获取更高的数量的分数,设置其权重weight = 15,boost_mode是multiply即相乘,得到 5 * 15 =75的得分;
attribute.type = type_hands ,权重次之weight=10,得到5*10=50的得分;其他为5
最后,将单个条件和组合条件统一起来,形成一张搜索查询的条件知识图:
本文暂时没有评论,来添加一个吧(●'◡'●)