Elasticsearch第11节 Filter、bool、exists

一、filter查询

filter查询是不计算相关性的,同时可以cache。因此,filter速度要快于query。

#批量插入数据(ES动态自动设置mapping)
POST /lib4/_bulk
{"index":{"_id":1}}
{"price":40,"itemID":"ID100123"}
{"index":{"_id":2}}
{"price":50,"itemID":"ID100124"}
{"index":{"_id":3}}
{"price":25,"itemID":"ID100125"}
{"index":{"_id":4}}
{"price":30,"itemID":"ID100126"}
{"index":{"_id":5}}
{"price":null,"itemID":"ID100127"}
//
#term查询某字段,按单一值匹配
GET /lib4/_search
{
  "query":{
    "bool":{
      "filter": [
        {"term":{"price":40}}  
      ]
    }
  }
}

#多个值查询,多查询参数之间是或者关系
GET /lib4/_search
{
  "query":{
    "bool":{
      "filter": [
        {"terms":{"price":[25,40]}}  
      ]
    }
  }
}

#没查出来
GET /lib4/_search
{
  "query":{
    "bool":{
      "filter": [
        {"term":{"itemID":"ID100125"}}  
      ]
    }
  }
}

#获取查看mapping,发现itemId类型是text,text类型默认是分词的,
#会将字母转换为小写,从而不区分大小写
GET /lib4/_mapping

#解决办法一:自建mapping,itemID不分词
DELETE /lib4
PUT /lib4
{
  "mappings": {
    "properties" : {
        "itemID" : {
          "type" : "text",
          "index": false
        },
        "price" : {
          "type" : "long"
        }
      }
  }
}

#解决办法二:查询参数的英文小写
GET /lib4/_search
{
  "query":{
    "bool":{
      "filter": [
        {"term":{"itemID":"id100125"}}  
      ]
    }
  }
}

二、bool过滤查询

可以实现组合过滤查询
must:必须满足的条件 and
should:可以满足也可以不满足的条件:or
must_not:绝对不可以的条件 and

GET /lib4/_search
{
  "query":{
    "bool":{
      "should": [
        {"term":{"itemID":"id100125"}},
        {"term":{"price":25}}
      ],
      "must_not": [
        {"term": {"price":"30"}},
        {"term": {"price":"40"}}
      ]
    }
  }
}


GET /lib4/_search
{
  "query":{
    "bool":{
      "should": [
        {"term":{"itemID":"id100125"}},
        {
          "bool": {
            "must": [
              {"term": {"itemID":"id100124"}},
              {"term": {"price":"50"}}
            ]
          }
        }
      ]
    }
  }
}

范围过滤

gt:>
lt:<
gte:>=
lte:<=

GET /lib4/_search
{
  "post_filter":{
    "range":{
      "price":{"gt":35, "lt": 50}
    }
  }
}

exists : 字段有值

//
#查询price有值的,null也不行
GET /lib4/_search
{
  "post_filter":{
    "exists":{
      "field":"price"
    }
  }
}

#查询price有值的,null也不行
GET /lib4/_search
{
  "query":{
    "bool":{
      "filter": {
        "exists": {
          "field": "price"
        }
      }
    }
  }
}

你可能感兴趣的:(Elasticsearch第11节 Filter、bool、exists)