Filter查询
filter是不计算相关性的,同时可以cache,因此,filter速度要块于query
-
数据准备
POST /lib3/user/_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"}
# 查看mapping
GET /lib3/_mapping
{
"lib3": {
"mappings": {
"user": {
"properties": {
"itemID": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"price": {
"type": "long"
}
}
}
}
}
} -
查询
GET /lib3/user/_search
{
"query": {
"bool": {
"filter": {
"term": {
"price": 40
}
}
}
}
}
# 查询多个值
GET /lib3/user/_search
{
"query": {
"bool": {
"filter": {
"terms": {
"price": [25,40]
}
}
}
}
}
# 查询不出来,因为itemID text类型并且进行了倒排索引,分词后转为小写存储
GET /lib3/user/_search
{
"query": {
"bool": {
"filter": {
"term": {
"itemID": "ID100124"
}
}
}
}
}
# 改为小写
GET /lib3/user/_search
{
"query": {
"bool": {
"filter": {
"term": {
"itemID": "id100124"
}
}
}
}
}
# 查询结果
{
"took": 3,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"failed": 0
},
"hits": {
"total": 1,
"max_score": 0,
"hits": [
{
"_index": "lib3",
"_type": "user",
"_id": "2",
"_score": 0,
"_source": {
"price": 50,
"itemID": "ID100124"
}
}
]
}
}
bool过滤查询
可以实现组合过滤查询
-
格式
{
"bool":{"must":[],"should":[],"must_not":[]}
}must:必须满足的条件 --and
should:可以满足也可以不满足的条件 --or
must_not:不需要满足的条件 --not
GET /lib3/user/_search
{
"query": {
"bool": {
"should": [
{"term": {"price": 25}},
{"term": {"itemID": "id100123"}}
]
, "must_not": [
{"term": {
"price": 40
}}
]
}
}
}
# 还可以嵌套
GET /lib3/user/_search
{
"query": {
"bool": {
"should": [
{ "term": {"price": 25}},
{
"bool": {
"must": [
{"term":{"itemID":"id100123"}},
{"term":{"price":40}}
]
}
}
]
}
}
}
范围过滤
gt: >
lt: <
gte: >=
-
lte: <=
# 范围过滤
GET /lib3/user/_search
{
"query": {
"bool": {
"filter": {
"range": {
"price": {
"gt": 25,
"lt": 50
}
}
}
}
}
}
# 非空过滤
GET /lib3/user/_search
{
"query": {
"bool": {
"filter": {
"exists": {
"field": "price"
}
}
}
}
}