python elasticsearch 日期聚合

2023-12-15 12:44:09
  1. 索引以及数据如下
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"
}
  1. 需求如下
    计算每个月每种类型的销售总额
  2. dsl
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"
              }
            }
          }
        }
      }
    }
  }
}
  1. python demo
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)

文章来源:https://blog.csdn.net/weixin_43632687/article/details/134880873
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。