Elasticsearch第12节 聚合查询
2019-06-17 本文已影响0人
小超_8b2f
一、聚合查询
//
#聚合查询 : sum
# "size": 0 去掉明细列表,只保留求和结果
GET /lib4/_search
{
"size": 0,
"aggs": {
"self_define_name_for_result": {
"sum": {"field":"price"}
}
}
}
#最小值:min
GET /lib4/_search
{
"size": 0,
"aggs": {
"price_min": {
"min": {"field":"price"}
}
}
}
#最大值:max
GET /lib4/_search
{
"size": 0,
"aggs": {
"price_max": {
"max": {"field":"price"}
}
}
}
#平均值:avg
GET /lib4/_search
{
"size": 0,
"aggs": {
"price_avg": {
"avg": {"field":"price"}
}
}
}
#基数:cardinality (互不相同的值的个数)
#select count(distinct column) from talbe_name
GET /lib4/_search
{
"size": 0,
"aggs": {
"price_cardinality": {
"cardinality": {"field":"price"}
}
}
}
#分组:terms 相当于group by
# 数字类型OK,text类型的不行
GET /lib4/_search
{
"size": 0,
"aggs": {
"price_of_group": {
"terms": {"field":"price"}
}
}
}
#结果(部分数据):
"aggregations" : {
"price_of_group" : {
"doc_count_error_upper_bound" : 0,
"sum_other_doc_count" : 0,
"buckets" : [
{
"key" : 25,
"doc_count" : 1
},
{
"key" : 30,
"doc_count" : 1
}
...... ]
}
}
#兴趣中包含xi huan字样的用户按年龄分组求年龄的平均值
# 并对分组年龄的平均值按降序排列
GET /myindex/_search
{
"size": 0,
"query": {
"match": {
"intrest": "xi huan"
}
},
"aggs": {
"post_date_group": {
"terms": {
"field": "age",
"order": {
"age_of_avg": "desc"
}
},
"aggs": {
"age_of_avg": {
"avg": {
"field": "age"
}
}
}
}
}
}
二、复合查询
GET /myindex/_search
{
"query":{
"bool":{
"must": [
{"match":{"intrest": "xi huan"}}
],
"must_not": [
{"match": {"intrest": "football"}}
],
"should": [
{"match": {"content": "t"}},
{"range": {"age": {"gte": 10,"lte": 30}}}
]
}
}
}
GET /myindex/_search
{
"query":{
"bool":{
"must": [
{"match":{"intrest": "xi huan"}}
],
"must_not": [
{"match": {"intrest": "football"}}
],
"should": [
{"match": {"content": "t"}}
],
"filter": {
"range": {"age": {"gte": 10,"lte": 30}}
}
}
}
}
三、constant_score
//
# constant_score
# 它将一个不变的常量评分应用于所有匹配的文档,它被经常用于
# 你只需要一个filter(例如评分查询)而没有其它查询的情况
# term被放置到了constant_score中,转成不评分的filter,
# 这种方式可以用来取代只有filter语句的bool查询
GET /myindex/_search
{
"query": {
"constant_score": {
"filter": {"term": {
"id": "120"
}},
"boost": 1.2
}
}
}