ElasticSearch 接口:文档多条件查询和范围查询

2022-04-22 0 By admin

一、多条件查询

1.1、Must 查询

假设想找出小米牌子,价格为3999元的。(must相当于数据库的&&)
GET请求 : http://127.0.0.1:9200/shopping/_search
附带JSON体如下:

{
  "query":{
    "bool":{
      "must":[{
        "match":{
          "category":"小米"
        }
      },{
        "match":{
          "price":3999.00
        }
      }]
    }
  }
}

返回结果如下:

{
  "took": 134,
  "timed_out": false,
  "_shards": {
    "total": 1,
    "successful": 1,
    "skipped": 0,
    "failed": 0
  },
  "hits": {
    "total": {
      "value": 1,
      "relation": "eq"
    },
    "max_score": 2.3862944,
    "hits": [
      {
        "_index": "shopping",
        "_type": "_doc",
        "_id": "ANQqsHgBaKNfVnMbhZYU",
        "_score": 2.3862944,
        "_source": {
          "title": "小米手机",
          "category": "小米",
          "images": "http://www.gulixueyuan.com/xm.jpg",
          "price": 3999
        }
      }
    ]
  }
}

1.2、Should 查询

假设想找出小米和华为的牌子。(should相当于数据库的||)
GET请求 : http://127.0.0.1:9200/shopping/_search
附带JSON体如下:

{
  "query":{
  "bool":{
    "should":[{
    "match":{
      "category":"小米"
    }
    },{
    "match":{
      "category":"华为"
    }
    }]
  },
    "filter":{
      "range":{
        "price":{
          "gt":2000
        }
      }
    }
  }
}

二、范围查询

假设想找出小米和华为的牌子,价格大于2000元的手机。
GET请求 : http://127.0.0.1:9200/shopping/_search
附带JSON体如下:

{
  "query":{
  "bool":{
    "should":[{
    "match":{
      "category":"小米"
    }
    },{
    "match":{
      "category":"华为"
    }
    }],
      "filter":{
        "range":{
          "price":{
            "gt":2000
          }
        }
      }
  }
  }
}

返回结果如下:

{
  "took": 72,
  "timed_out": false,
  "_shards": {
    "total": 1,
    "successful": 1,
    "skipped": 0,
    "failed": 0
  },
  "hits": {
    "total": {
      "value": 1,
      "relation": "eq"
    },
    "max_score": 1.3862942,
    "hits": [
      {
        "_index": "shopping",
        "_type": "_doc",
        "_id": "ANQqsHgBaKNfVnMbhZYU",
        "_score": 1.3862942,
        "_source": {
          "title": "小米手机",
          "category": "小米",
          "images": "http://www.gulixueyuan.com/xm.jpg",
          "price": 3999
        }
      }
    ]
  }
}