bool 搜索的常用格式,典型案例如下所示:

  1. {
  2. "bool": {
  3. "must": { },
  4. "must_not": { },
  5. "should": { },
  6. "filter": { }
  7. }
  8. }

bool 查询有2个规则很重要

  • 当 must 条件存在的时候,should 可以都不满足
  • 当 must 条件不存在的时候,should 条件必须满足一个

    案例 1

    比如 MySQl有如下类似的条件
    1. SELECT * FROM tb
    2. Where status = 1 AND language != 'french' AND (author = 'John' OR author = 'Tom')
    那么转换为 ES 可以看做是
    1. {
    2. "bool": {
    3. "must": { "match": { "status": 1 }},
    4. "must_not": { "match": { "language": "french" }},
    5. "should": { "match": { "author": "John Tom" }},
    6. "filter": { "range": { "length" : { "gt" : 30 }} }
    7. }
    8. }

    案例 2

    下图是另外一个场景,也就是我上文提到的:当 must 条件不存在,那么 should 条件必须满足一个。
    MySQL 的 or 也就是必须要满足一个,所以整体可以使用 or 来拼接。
    image.png
    文字版本如下所示
    1. GET /article/_search
    2. {
    3. "query": {
    4. "bool": {
    5. "should": [
    6. {
    7. "term": {"articleID": {"value": "KDKE-B-9947-#kL5"}}
    8. },
    9. {
    10. "bool": {
    11. "must": [
    12. {"term": {"userID": {"value": "2"}}},
    13. {"term": {"postDate": {"value": "2017-01-01"}}}
    14. ]
    15. }
    16. }]}}}

    案例 4

    该案例类似于 案例 3。
    对应的 SQL 为
    1. select * from paper where date= "2018-10-11" or (uid=1 and publish= 1)
    对应的 json 为
    1. {
    2. "query": {
    3. "bool": {
    4. "should": [
    5. {"term": {"date": "2018-10-11"}},
    6. {"bool": {
    7. "must": [
    8. {"term": {"uID": "1"}},
    9. {"term": {"publish": true}}
    10. ]
    11. }}
    12. ]
    13. }
    14. }
    15. }

    案例 5

    SQL 为
    1. select * from paperwhere
    2. (date="2018-10-11" or uID= 1) and pID!="7ec0e0e5-a4b0-46d7-af56-5b3eab477aea"

JSON为

  1. {
  2. "query": {
  3. "bool": {
  4. "should": [
  5. {"term": {"date":"2018-10-11"}},
  6. {"term": {"uID":1}}
  7. ],
  8. "must_not": [
  9. {"term": {"pID": "7ec0e0e5-a4b0-46d7-af56-5b3eab477aea"}}
  10. ]
  11. }
  12. }
  13. }

案例 6

SQL

  1. SQL :
  2. SELECT * FROM order_v2
  3. WHERE
  4. (order_no = '202003131209120999' AND shop_id >= 10 AND shop_id <= 200 ) OR tag IN (1,2,3,4,5)

JSON

  1. {
  2. "query": {
  3. "bool": {
  4. "must": [
  5. {"term": {"order_no": "202003131209120999"}},
  6. {
  7. "range": {
  8. "shop_id": {
  9. "gte": 10,
  10. "lte": 200
  11. }
  12. }
  13. }
  14. ],
  15. "should": [
  16. {
  17. "terms": {
  18. "tag": [1,2,3,4,5]
  19. }
  20. }
  21. ]
  22. }
  23. }
  24. }

结语

单字段,多条件
多字段搜索,boost
bool
query
dis_max tie_breaker