- 索引以及数据如下
bash
PUT dateagg
{
"mappings": {
"properties": {
"charge":{
"type": "double"
},
"types":{
"type": "keyword"
},
"create_date":{
"type": "date",
"format": "yyyy-MM-dd||strict_date_optional_time ||epoch_millis||E MMM dd H:m:s z y"
}
}
}
}
POST dateagg/_doc/1
{
"charge":"900",
"types":"水果",
"create_date":"2020-09-01"
}
POST dateagg/_doc/2
{
"charge":"800",
"types":"水果",
"create_date":"2020-09-30"
}
POST dateagg/_doc/3
{
"charge":"1900",
"types":"熟食",
"create_date":"2021-10-01"
}
POST dateagg/_doc/4
{
"charge":"100",
"types":"熟食",
"create_date":"2023-12-31"
}
- 需求如下
计算每个月每种类型的销售总额 - dsl
bash
GET dateagg/_search
{
"query": {
"match_all": {}
},"aggs": {
"types": {
"terms": {
"field": "types"
},"aggs": {
"date": {
"date_histogram": {
"field": "create_date",
"interval": "month",
"format": "yyyy-MM",
"min_doc_count":1
},"aggs": {
"sum": {
"sum": {
"field": "charge"
}
}
}
}
}
}
}
}
- python demo
python
from elasticsearch_dsl import connections,Search,Q as esQ
conn = connections.create_connection(hosts=['192.168.214.134'],port=9200,http_auth="elastic:ellischen")
index = 'dateagg'
search = Search(using=conn,index=index)
query = esQ('match_all',**{})
search.query = query
search.extra(size=0)
search.aggs.bucket('types','terms',field="types").bucket('date',"date_histogram",field="create_date",format="yyyy-MM",interval="month",min_doc_count=1).metric("sum","sum",field="charge")
response = search.execute().aggregations.to_dict()
print(response)