bool 搜索的常用格式,典型案例如下所示:
{
"bool": {
"must": { },
"must_not": { },
"should": { },
"filter": { }
}
}
bool 查询有2个规则很重要
比如 MySQl有如下类似的条件
SELECT * FROM tb
Where status = 1 AND language != 'french' AND (author = 'John' OR author = 'Tom')
那么转换为 ES 可以看做是
{
"bool": {
"must": { "match": { "status": 1 }},
"must_not": { "match": { "language": "french" }},
"should": { "match": { "author": "John Tom" }},
"filter": { "range": { "length" : { "gt" : 30 }} }
}
}
下图是另外一个场景,也就是我上文提到的:当 must 条件不存在,那么 should 条件必须满足一个。
MySQL 的 or 也就是必须要满足一个,所以整体可以使用 or 来拼接。
文字版本如下所示
GET /article/_search
{
"query": {
"bool": {
"should": [
{
"term": {"articleID": {"value": "KDKE-B-9947-#kL5"}}
},
{
"bool": {
"must": [
{"term": {"userID": {"value": "2"}}},
{"term": {"postDate": {"value": "2017-01-01"}}}
]
}
}]}}}
该案例类似于 案例 3。
对应的 SQL 为
select * from paper where date= "2018-10-11" or (uid=1 and publish= 1)
对应的 json 为
{
"query": {
"bool": {
"should": [
{"term": {"date": "2018-10-11"}},
{"bool": {
"must": [
{"term": {"uID": "1"}},
{"term": {"publish": true}}
]
}}
]
}
}
}
SQL 为
select * from paperwhere
(date="2018-10-11" or uID= 1) and pID!="7ec0e0e5-a4b0-46d7-af56-5b3eab477aea"
JSON为
{
"query": {
"bool": {
"should": [
{"term": {"date":"2018-10-11"}},
{"term": {"uID":1}}
],
"must_not": [
{"term": {"pID": "7ec0e0e5-a4b0-46d7-af56-5b3eab477aea"}}
]
}
}
}
SQL
SQL :
SELECT * FROM order_v2
WHERE
(order_no = '202003131209120999' AND shop_id >= 10 AND shop_id <= 200 ) OR tag IN (1,2,3,4,5)
JSON
{
"query": {
"bool": {
"must": [
{"term": {"order_no": "202003131209120999"}},
{
"range": {
"shop_id": {
"gte": 10,
"lte": 200
}
}
}
],
"should": [
{
"terms": {
"tag": [1,2,3,4,5]
}
}
]
}
}
}
单字段,多条件
多字段搜索,boost
bool
query
dis_max tie_breaker