python elasticsearch 日期聚合

  1. 索引以及数据如下
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"
}
  1. 需求如下
    计算每个月每种类型的销售总额
  2. 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"
              }
            }
          }
        }
      }
    }
  }
}
  1. 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)
相关推荐
邓熙榆几秒前
Logo语言的网络编程
开发语言·后端·golang
hunter2062064 分钟前
用opencv生成视频流,然后用rtsp进行拉流显示
人工智能·python·opencv
S-X-S1 小时前
项目集成ELK
java·开发语言·elk
超级阿飞1 小时前
利用Kubespray安装生产环境的k8s集群-实施篇
elasticsearch·容器·kubernetes
Johaden2 小时前
EXCEL+Python搞定数据处理(第一部分:Python入门-第2章:开发环境)
开发语言·vscode·python·conda·excel
小虎牙^O^3 小时前
2024春秋杯密码题第一、二天WP
python·密码学
梦魇梦狸º4 小时前
mac 配置 python 环境变量
chrome·python·macos
查理零世4 小时前
算法竞赛之差分进阶——等差数列差分 python
python·算法·差分
ByteBlossom6666 小时前
MDX语言的语法糖
开发语言·后端·golang
查士丁尼·绵6 小时前
面试-字符串1
python