百度es的or查詢件炉,大多數(shù)的博客會(huì)告訴你用should勘究,但是should應(yīng)該加在哪兒,有很多的謬誤斟冕,導(dǎo)致query和實(shí)際查詢語義不一樣口糕。
例如實(shí)現(xiàn)"name"=="a" and ("city" == "b" or "city" == "c")
,是不是以為這樣就可以?
{
"query": {
"bool": {
"must": [{
"match_phrase": {
"name": "a"
}
}],
"should": [{
"match_phrase": {
"city": "b"
}
},
{
"match_phrase": {
"city": "c"
}
}]
}
}
}
是不可以的磕蛇,當(dāng)must和should同級(jí)時(shí)景描,should只影響評分_score十办,而不具備過濾功能,查詢結(jié)果見圖1超棺,city=='d'的doc也返回了向族,只不過評分低一些。
怎么辦呢棠绘?有兩種解決方案件相。
1、將should放到must中氧苍,表示or條件必須成立,像這樣夜矗,看圖2,結(jié)果和我們語義是一致的候引。
{
"query": {
"bool": {
"must": [
{
"term": {
"name": "a"
}
},
{
"bool": {
"should": [
{
"term": {
"city": "b"
}
},
{
"term": {
"city": "c"
}
}
]
}
}
]
}
}
}
2侯养、指定 "minimum_should_match"。
擴(kuò)展.
等價(jià)于 year==2020 and learn_season in (2,20,21,22,...) and main_grade in (1,2,3) and lesson_stop_time >=1598244100 and lesson_assistant_status ==1 and (assistant_preclass_live_duration > 0 or assistant_postclass_live_duration > 0)
{
"index": "idl_assistant_lesson_all_action",
"type": "_doc",
"query": {
"bool": {
"filter": [
{
"term": {
"year": 2020
}
},
{
"terms": {
"learn_season": [
"2",
"20",
"21",
"22",
"23",
"24",
"25",
"26",
"27",
"28",
"29",
"210",
"211",
"212",
"213",
"214",
"215"
]
}
},
{
"terms": {
"main_grade": [
"2",
"3",
"4"
]
}
},
{
"terms": {
"main_subject": [
"1",
"2",
"3"
]
}
},
{
"range": {
"lesson_stop_time": {
"lte": "1598244100"
}
}
},
{
"term": {
"lesson_assistant_status": 1
}
},
{
"bool": {
"should": [
{
"range": {
"assistant_preclass_live_duration": {
"gt": "0"
}
}
},
{
"range": {
"assistant_postclass_live_duration": {
"gt": "0"
}
}
}
]
}
}
]
}
},
"_source": {
"includes": [
"course_id",
"course_name",
"lesson_id",
"lesson_name",
"assistant_uid",
"lesson_start_time",
"lesson_stop_time"
]
},
"sort": [
{
"lesson_start_time": {
"order": "desc"
}
},
{
"lesson_id": {
"order": "asc"
}
},
{
"assistant_uid": {
"order": "asc"
}
}
],
"from": 0,
"size": 20,
"search_after": [
"1598232600",
"368801",
"2366998326"
]
}
擴(kuò)展之又.
or 查詢中有不等于怎么辦澄干?百度會(huì)告訴你 用must_not逛揩,
例如 city== a or city != c
,ES 不支持不等于運(yùn)算符, must_not是和bool同級(jí)使用的麸俘,怎么辦呢辩稽?
轉(zhuǎn)變思路,city != c
是不是就是等價(jià)于 city > c or city < c
从媚,query就可以這么寫逞泄。
{
"query": {
"bool": {
"must": [
{
"bool": {
"should": [
{
"term": {
"city": "a"
}
},
{
"range": {
"city": {
"lt": "c"
}
}
},
{
"range": {
"city": {
"gt": "c"
}
}
}
]
}
}
]
}
}
}
that's all,enjoy~