ES 时间分组聚合查询

1,354 阅读1分钟

正常业务逻辑中,会出现大量的数据统计,比如说分组聚合查询,根据月进行数据的统计

date_histogram的用法

{
  "size": 0,
  "aggs": {
    "groupDate": {
      "date_histogram": {
        "field": "time",     # 查询字段
        "interval": "month", # 聚合时间间隔:year, quarter, month, week, day, hour, minute, second(年份、季度、月、周、日、小时、分钟、秒)
        "format": "yyyy-MM", # 格式化时间
		"time_zone":"+08:00" # 在es中日期支持时区的表示方法,这样就相当于东八区的时间
      }
    }
  }
}

按月聚合查询数据

GET /study/study_report/_search
{
  "query": {
    "constant_score": {
      "filter": {
        "bool": {
          "must": [
            {
              "term": {
                "course_subjects_name": "经济法基础"
              }
            },
            {
              "term": {
                "user_id": 1939399
              }
            },
            {
              "range": {
                "dt": {
                  "from": "20220801",
                  "include_lower": true,
                  "include_upper": true,
                  "to": "20220922"
                }
              }
            }
          ]
        }
      }
    }
  },
  "size": 0,
  "aggs": {
    "sales_per_month": {
      "date_histogram": {
        "field": "time",
        "interval": "month",
        "format": "yyyyMM",
        "time_zone":"+08:00"
      },
      "aggs": {
        "sum_count_question": {
          "sum": {
            "field": "count_question"
          }
        },
        "sum_course_cat_id": {
          "sum": {
            "field": "course_cat_id"
          }
        }
      }
    }
  }
}

管道聚合

管道聚合 Pipeline aggregations

参考链接:🔗

date_histogram的用法

管道聚合