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)
相关推荐
小猿姐4 小时前
唯品会大规模数据库云原生实践:基于 KubeBlocks 管理数千实例的统一运维之路
运维·elasticsearch·云原生
SelectDB14 小时前
Apache Doris Python UDF:让 SQL 直接调用 Python 生态,支撑 Agent 时代复杂业务逻辑
大数据·数据库·python
Elasticsearch21 小时前
使用 Elastic Agent Builder 和 Sarvam AI 构建多语言语音 agent
elasticsearch
荣码21 小时前
GraphRAG:普通RAG只能回答"点"的问题,我踩了4个坑才搞懂
java·python
金銀銅鐵1 天前
[Python] 基于欧几里得算法,实现分数约分计算器
python·数学
Lyn_Li1 天前
Kaggle Top 5 | 198只股票、200条数据的金融预测——BattleFin高分方案从零复现
python·kaggle·比赛复盘·金融预测
小九九的爸爸2 天前
前端想要入门Agent开发,要具备哪些Python基础?
python·agent·ai编程
阿耶同学2 天前
手把手教你用 LangGraph 搭建三层嵌套 Agent 架构
python·程序员
花酒锄作田2 天前
Pydantic校验配置文件
python
hboot2 天前
AI工程师第四课 - 深度学习入门
pytorch·python·神经网络