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)
相关推荐
BioRunYiXue几秒前
Nature Methods:CellVoyager 自主 AI 智能体开启生物数据分析新时代
大数据·开发语言·前端·javascript·人工智能·数据挖掘·数据分析
tottoramen6 分钟前
如何安装龙虾
python
QC·Rex15 分钟前
AI Agent 任务规划实战:从 ReAct 到 Plan-and-Solve 的完整指南
人工智能·python·react
kcuwu.1 小时前
Python面向对象:封装、继承、多态
开发语言·python
YuanDaima20481 小时前
LangChain基础配置与对话模型实战
人工智能·python·langchain·大模型·智能体·langgraph
一定要AK1 小时前
Java流程控制
java·开发语言·笔记
河西石头1 小时前
分享python项目与开源python项目中的效率法宝--requirements文件的使用
开发语言·python·requirements文件·批量安装python依赖·python虚拟环境配置
不懒不懒1 小时前
【卷积神经网络作业实现人脸的关键点定位功能】
开发语言·python
321.。1 小时前
Linux 进程控制深度解析:从创建到替换的完整指南
linux·开发语言·c++·学习