ElasticSearch(聚合)

88 阅读1分钟

Terms aggregation

首先是terms 聚合相当于我们sql里面的group by

Example:select * from cars group by price

GET cars/_search
{
    "query": {
        "bool": {
            "must": [
                {
                    "match_all": {}
                }
            ]
        }
    },
    "from": 0,
    "size": 0,
    "aggregations": {
        "price": {//此处名称为自定义可与字段名字相同
            "terms": {
                "field": "price",
                "order": {
                  "_key": "asc"//排序为升序相当于order by
                }
            }
        }
    }
}

最大值(max)、最小值(min)、平均值(avg)、求和(sum)

GET cars/_search
{
    "query": {
        "bool": {
            "must": [
                {
                    "match_all": {}
                }
            ]
        }
    },
    "from": 0,
    "size": 0,
    "aggregations": {
        "max_price": {
            "max": {
                "field": "price"
            }
        }
    }
}

stats会显示所有聚合指标

GET cars/_search
{
    "query": {
        "bool": {
            "must": [
                {
                    "match_all": {}
                }
            ]
        }
    },
    "from": 0,
    "size": 0,
    "aggregations": {
        "price": {
            "stats": {
                "field": "price"
            }
        }
    }
}

结果示例

image.png

另外还有range聚合(范围),date_range 聚合(时间范围),cardinality 聚合(表示去重)