ElasticSearch(四):Filter查询、聚合查询
1. 简述
Filter查询时不计算相关性的,同时可以进行缓存,因此,Filter查询的速度要快于query查询;
2. 数据准备
POST /lib9/items/_bulk
{"index": {"id": 1}}
{"price": 40,"itemID": "ID100123"}
{"index": {"_id": 2}}
{"price": 50,"itemID": "ID100124"}
{"index": {"_id": 3}}
{"price": 25,"itemID": "ID100124"}
{"index": {"_id": 4}}
{"price": 30,"itemID": "ID100125"}
{"index": {"_id": 5}}
{"price": null,"itemID": "ID100127"}
3. filter查询
3.1 简单过滤查询
# 查询price=40的文档
GET /lib9/items/_search
{
"post_filter": {
"term": {
"price": 40
}
}
}
# 查询price等于25或40的文档
GET /lib9/items/_search
{
"post_filter": {
"terms": {
"price": [
25,
40
]
}
}
}
# 查询itemID等于ID100123的文档(注意在这里要写成小写id)
GET /lib9/items/_search
{
"post_filter": {
"term": {
"itemID": "id100123"
}
}
}
3.2 bool过滤查询
可以实现组合过滤查询
# 格式
{
"bool": {
"must": [],
"should": [],
"must_not": []
}
}
注意
**1. must:必须要满足的条件 —and
- should: 可以满足也可以不满足的条件 —or
must_not:不需要满足的条件 —not**
GET /lib9/items/_search
{
“post_filter”: {"bool": {
"should": [
{
"term": {
"price": 25
}
},
{
"term": {
"itemID": "id100123"
}
}
],
"must_not": [
{
"term": {
"price": 30
}
}
]
}
}
}GET /lib9/items/_search
{
“post_filter”: {"bool": {
"should": [
{
"term": {
"itemID": "id100123"
}
},
{
"bool": {
"must": [
{
"term": {
"itemID": "id100124"
}
},
{
"term": {
"price": 40
}
}
]
}
}
]
}
}
}
3.3 range范围过滤
gt:>
lt:<
gte:>=
lte:<=
GET /lib9/items/_search
{
"post_filter": {
"range": {
"price": {
"gt": 35,
"lt": 50
}
}
}
}
3.4 过滤非空
GET /lib9/items/_search
{
"query": {
"bool": {
"filter": {
"exists": {
"field": "price"
}
}
}
}
}
GET /lib9/items/_search
{
"query": {
"constant_score": {
"filter": {
"exists": {
"field": "price"
}
}
}
}
}
3.5 过滤器缓存
ElasticSearch有一种特殊的缓存,即过滤器缓存(filter cache),用来存储过滤器的结果,被缓存的过滤器并不需要消耗过多的内存,而且可供后续所有与之相关的查询重复使用,从而极大地提高了查询性能。
注意:ElasticSearch并不是默认缓存所有过滤器,
以下过滤器默认不缓存:
numeric_range
script
geo_bbox
geo_distance
geo_distance_range
geo_polygon
geo_shape
and
or
not以下过滤器默认开启缓存
exists
missing
range
term
terms开启方式:在filter查询语句后边加上 “_catch”:true
4. 聚合查询
sum
GET /lib9/items/_search
{
“size”:0,
“aggs”: {"price_of_sum": {
"sum": {
"field": "price"
}
}
}
}
运行结果
{
"took": 6,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"skipped": 0,
"failed": 0
},
"hits": {
"total": 5,
"max_score": 0,
"hits": []
},
"aggregations": {
"price_of_sum": {
"value": 160
}
}
}
min
GET /lib9/items/_search
{
“size”: 0,
“aggs”: {"price_of_min": {
"min": {
"field": "price"
}
}
}
}
运行结果
{
"took": 4,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"skipped": 0,
"failed": 0
},
"hits": {
"total": 5,
"max_score": 0,
"hits": []
},
"aggregations": {
"price_of_min": {
"value": 30
}
}
}
- max、avg同上
terms:分组
GET /lib9/items/_search
{
“size”: 0,
“aggs”: {"price_group_by": {
"terms": {
"field": "price"
}
}
}
}
还没有评论,来说两句吧...