es的date类型字段按照原生格式进行分组聚合

PUT student2
{
"mappings": {"properties": {"name": {"type": "text","analyzer": "standard"  // 使用标准分析器,适合姓名字段},"birthday": {"type": "date","format": "yyyy||yyyy-MM||yyyy-MM-dd"  // 日期格式,可以根据需求调整},"age": {"type": "integer"  // 年龄字段,使用整型},"gender": {"type": "keyword"  // 性别字段,使用 keyword 类型来避免分词},"email": {"type": "keyword"  // 使用 keyword 类型来存储不需要分词的电子邮件地址},"address": {"type": "text"  // 地址字段,适合使用全文本分词},"registration_date": {"type": "date","format": "yyyy-MM-dd'T'HH:mm:ss"  // 注册日期,包含时间},"is_active": {"type": "boolean"  // 是否激活标记,使用布尔类型}}
}
} 

插入数据

POST student1/_doc/1
{"name": "Alice","birthday": "2000","age": 24,"gender": "female","email": "alice@example.com","address": "123 Maple Street, Springfield","registration_date": "2022-08-01T09:30:00","is_active": true
}POST student1/_doc/2
{"name": "Bob","birthday": "1998-11","age": 26,"gender": "male","email": "bob@example.com","address": "456 Oak Avenue, Shelbyville","registration_date": "2023-01-10T14:00:00","is_active": true
}POST student1/_doc/3
{"name": "Charlie","birthday": "1995-03-25","age": 29,"gender": "male","email": "charlie@example.com","address": "789 Birch Road, Capital City","registration_date": "2021-07-15T11:00:00","is_active": false
}POST student1/_doc/4
{"name": "Diana","birthday": "1999","age": 25,"gender": "female","email": "diana@example.com","address": "101 Pine Lane, Townsville","registration_date": "2020-12-05T08:00:00","is_active": true
}

执行查询

GET student2/_search
{"size": 0,"aggs": {"birthday_by_original_format": {"terms": {"script": {"source": """if (params['_source']['birthday'] != null) {return params['_source']['birthday'].toString();}return null;"""},"size": 10}}}
}

得到结果:

{"took": 25,"timed_out": false,"_shards": {"total": 1,"successful": 1,"skipped": 0,"failed": 0},"hits": {"total": {"value": 4,"relation": "eq"},"max_score": null,"hits": []},"aggregations": {"birthday_by_original_format": {"doc_count_error_upper_bound": 0,"sum_other_doc_count": 0,"buckets": [{"key": "1995","doc_count": 1},{"key": "1998-11","doc_count": 1},{"key": "1999-07-20","doc_count": 1},{"key": "2000-05-15","doc_count": 1}]}}
}

查询语句写为java:

import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.RestClient;
import org.apache.http.HttpHost;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.script.ScriptType;
import org.elasticsearch.script.Script;import java.io.IOException;
import java.util.Collections;
import java.util.List;public class ElasticsearchAggregationExample {public static void main(String[] args) {// 创建 Elasticsearch 客户端RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http"))  // 替换为你的 Elasticsearch 地址);try {// 构建查询请求SearchRequest searchRequest = new SearchRequest("student2");  // 替换为你的索引名称SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();// 构建聚合String scriptSource = "if (params['_source']['birthday'] != null) { " +"  return params['_source']['birthday'].toString(); " +"} " +"return null;";TermsAggregationBuilder aggregationBuilder = AggregationBuilders.terms("birthday_by_original_format").script(new Script(ScriptType.INLINE, "painless", scriptSource, Collections.emptyMap())).size(10);  // 设置返回的桶数量// 将聚合添加到查询中sourceBuilder.aggregation(aggregationBuilder);sourceBuilder.size(0);  // 不返回具体文档,只返回聚合结果searchRequest.source(sourceBuilder);// 执行查询SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);// 解析聚合结果Terms terms = searchResponse.getAggregations().get("birthday_by_original_format");List<? extends Terms.Bucket> buckets = terms.getBuckets();for (Terms.Bucket bucket : buckets) {String key = bucket.getKeyAsString();  // 获取聚合的 key(原始的 birthday 值)long docCount = bucket.getDocCount();  // 获取文档数量System.out.println("Key: " + key + ", Doc Count: " + docCount);}} catch (IOException e) {e.printStackTrace();} finally {// 关闭客户端try {client.close();} catch (IOException e) {e.printStackTrace();}}}
}

终极解决方案:
给mapping的所有date类型字段添加子类型

PUT /student3
{"mappings": {"properties": {"address": {"type": "text"},"age": {"type": "integer"},"birthday": {"type": "date","format": "yyyy||yyyy-MM||yyyy-MM-dd","fields": {                "raw": {                "type": "keyword"}}},"email": {"type": "keyword"},"events": {"type": "nested","properties": {"event_date": {"type": "date","format": "yyyy||yyyy-MM||yyyy-MM-dd","fields": {                "raw": {                "type": "keyword"}}},"event_type": {"type": "keyword"}}},"gender": {"type": "keyword"},"is_active": {"type": "boolean"},"name": {"type": "text","analyzer": "standard"},"registration_date": {"type": "date","format": "yyyy-MM-dd'T'HH:mm:ss","fields": {                "raw": {                "type": "keyword"}}}}}
}

插入数据:

POST student1/_doc/1
{"name": "Alice","birthday": "2000","age": 24,"gender": "female","email": "alice@example.com","address": "123 Maple Street, Springfield","registration_date": "2022-08-01T09:30:00","is_active": true,"events": [{"event_date": "2022","event_type": "graduation"},{"event_date": "2023","event_type": "birthday"}]
}POST student1/_doc/2
{"name": "Bob","birthday": "1998-11","age": 26,"gender": "male","email": "bob@example.com","address": "456 Oak Avenue, Shelbyville","registration_date": "2023-01-10T14:00:00","is_active": true,"events": [{"event_date": "2022-06","event_type": "meeting"}]
}POST student1/_doc/3
{"name": "Charlie","birthday": "1995-03-25","age": 29,"gender": "male","email": "charlie@example.com","address": "789 Birch Road, Capital City","registration_date": "2021-07-15T11:00:00","is_active": false,"events": [{"event_date": "2021-10-10","event_type": "conference"},{"event_date": "2022-02-20","event_type": "workshop"},{"event_date": "2023-04-05","event_type": "meeting"}]
}POST student1/_doc/4
{"name": "Diana","birthday": "1999-07-20","age": 25,"gender": "female","email": "diana@example.com","address": "101 Pine Lane, Townsville","registration_date": "2020-12-05T08:00:00","is_active": true,"events": [{"event_date": "2022-11-10","event_type": "webinar"}]
}

根据嵌套子字段的date类型字段聚合

GET /student3_new/_search
{"size": 0,"aggs": {"nested_events": {"nested": {"path": "events"},"aggs": {"event_date_groups": {"terms": {"field": "events.event_date.raw", "size": 10}}}}}
}

聚合结果:

{"took": 2,"timed_out": false,"_shards": {"total": 1,"successful": 1,"skipped": 0,"failed": 0},"hits": {"total": {"value": 4,"relation": "eq"},"max_score": null,"hits": []},"aggregations": {"nested_events": {"doc_count": 7,"event_date_groups": {"doc_count_error_upper_bound": 0,"sum_other_doc_count": 0,"buckets": [{"key": "2021-10-10","doc_count": 1},{"key": "2022","doc_count": 1},{"key": "2022-02-20","doc_count": 1},{"key": "2022-06","doc_count": 1},{"key": "2022-11-10","doc_count": 1},{"key": "2023","doc_count": 1},{"key": "2023-04-05","doc_count": 1}]}}}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.rhkb.cn/news/5307.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

汇编与逆向(一)-汇编工具简介

RadASM是一款著名的WIN32汇编编辑器&#xff0c;支持MASM、TASM等多种汇编编译器&#xff0c;Windows界面&#xff0c;支持语法高亮&#xff0c;自带一个资源编辑器和一个调试器。 一、汇编IDE工具&#xff1a;RadASM RadASM有内置的语言包 下载地址&#xff1a;RadASM asse…

基于STM32的智能门锁安防系统(开源)

目录 项目演示 项目概述 硬件组成&#xff1a; 功能实现 1. 开锁模式 1.1 按键密码开锁 1.2 门禁卡开锁 1.3 指纹开锁 2. 功能备注 3. 硬件模块工作流程 3.1 步进电机控制 3.2 蜂鸣器提示 3.3 OLED显示 3.4 指纹与卡片管理 项目源代码分析 1. 主程序流程 (main…

AUTOSAR OS模块详解(三) Alarm

AUTOSAR OS模块详解(三) Alarm 本文主要介绍AUTOSAR OS的Alarm&#xff0c;并对基于英飞凌Aurix TC3XX系列芯片的Vector Microsar代码和配置进行部分讲解。 文章目录 AUTOSAR OS模块详解(三) Alarm1 简介2 功能介绍2.1 触发原理2.2 工作类型2.3 Alarm启动方式2.4 Alarm配置2.5…

YOLO目标检测1

一. 参考资料 《YOLO目标检测》 by 杨建华博士 二. 背景 2.1 目标检测发展简史 2014年&#xff0c;RCNN问世&#xff0c;R-CNN的思路是先使用一个搜索算法从图像中提取出若干感兴趣区域(region of interest&#xff0c;RoI)&#xff0c;然后使用一个卷积神经网络(convolutio…

【Qt 常用控件】显示类控件——QLabel

目录 1.QLabel 1.1 textFormat 文本类型 普通文本和富文本 Markdown格式 1.2 alignment 文本对齐方式 1.3 wordWrap 自动换行 1.4 indent 文本缩进 1.5 margin 边距 1.6 buddy&#xff0c;qlabel伙伴 1.7 pixmap图片 和 scaledContents自动填充 1.QLabel 功能&#x…

vif-方差膨胀因子计算

vif-方差膨胀因子 使用statsmodels中的variance_inflation_factor&#xff0c;数据集使用乳腺癌数据集 import pandas as pd import numpy as np from sklearn.datasets import load_breast_cancer from tqdm import notebook from statsmodels.stats.outliers_influence impor…

查看电脑或笔记本CPU的核心数方法及CPU详细信息

一、通过任务管理器查看 1.打开任务管理器 可以按下“Ctrl Shift Esc”组合键&#xff0c;或者按下“Ctrl Alt Delete”组合键后选择“任务管理器”来打开。 2.查看CPU信息 在任务管理器界面中&#xff0c;点击“性能”标签页&#xff0c;找到CPU使用记录区域&#xff0c…

数据恢复常见故障(四)关键信号的耦合电容撞件后导致SATA前端通信异常

数据恢复常见故障&#xff08;四&#xff09;关键信号耦合电容撞件后导致SATA前端通信异常 SATA固态硬盘SATA差分信号上有耦合电容&#xff0c;电容被撞件后&#xff0c;偏移&#xff0c;导致接触不良&#xff0c;引起SATA前端信号通信异常&#xff0c;故障现象表现为不认盘&a…

[HCTF 2018]WarmUp

题目&#xff1a;一上来给了个图片还是很懵的&#xff0c;于是尝试查看一下源代码&#xff1a;发现有提示&#xff1a;于是访问source.php得到了php代码&#xff1a;(这里将代码和代码分析放一块) <?phphighlight_file(__FILE__); class emmm{public static function chec…

MYSQL数据库基础-01.数据库的基本操作

数据库的语法是大小写不敏感的&#xff0c;可以使用大写&#xff0c;也可以使用小写。 每条语句要以&#xff1b;结尾&#xff0c;可以多行输入。 名称不能是关键字,若想用关键字命名,要用反引号 引起来。 目录 一.数据库的基本操作 1.创建数据库&#xff1a; 2.查看数据库…

Decode Global专注金融创新,构建便捷的交易平台

随着金融市场持续进阶&#xff0c;越来越多的年轻正在涌入金融交易的体系中&#xff0c;针对当下年轻人崇尚精简&#xff0c;优中取优的特点&#xff0c;Decode Global紧跟金融市场发展的步伐&#xff0c;不断创新体验&#xff0c;致力于打造一个精简快捷&#xff0c;安全便捷的…

系统思考—转型

我们大多数问题的来源是&#xff1a;人们的思考方式与大自然的运作方式之间的差异。——葛雷果利贝特森&#xff08;人类学家、生物学家及系统思考先驱&#xff09; 在企业转型的过程中&#xff0c;许多企业创始人常常面临一个困境——过去的成功经验和旧有的思维方式&#xf…

Flutter:carousel_slider 横向轮播图、垂直轮播公告栏实现

安装依赖 carousel_slider: ^5.0.01、垂直滚动公告栏 import package:carousel_slider/carousel_options.dart;// 垂直滚动公告栏Widget _buildNotice() {return <Widget>[<Widget>[TDImage(assetUrl: "assets/img/home11.png",width: 60.w,height: 60.w…

【二叉树的深搜】计算布尔二叉树的值 求根节点到叶节点数字之和

文章目录 2331. 计算布尔二叉树的值解题思路&#xff1a;后序遍历129. 求根节点到叶节点数字之和解题思路&#xff1a;深度优先搜索 前序遍历 2331. 计算布尔二叉树的值 2331. 计算布尔二叉树的值 给你一棵 完整二叉树 的根&#xff0c;这棵树有以下特征&#xff1a; 叶子节…

【高阶数据结构】布隆过滤器(BloomFilter)

1. 概念 1.1 背景引入 背景&#xff1a;在计算机软件中&#xff0c;一个常见的需求就是 在一个集合中查找一个元素是否存在 &#xff0c;比如&#xff1a;1. Word 等打字软件需要判断用户键入的单词是否在字典中存在 2. 浏览器等网络爬虫程序需要保存一个列表来记录已经遍历过…

偏序关系.

一、偏序&#xff08;半序&#xff09;关系 偏序关系 自反反对称传递性 二、全序&#xff08;线序、链&#xff09;关系 三、偏序集中的重要元素 1. 极大元与极小元 极大元找所在集合的一个或几个最高点&#xff1b; 极小元找所在集合的一个或几个最低点。 2. 最大元与最小…

国产编辑器EverEdit - 列编辑模式

1 列模式 1.1 应用背景 在编辑CSV格式&#xff0c;或者比较规整的配置文件时&#xff0c;可能会用到一列的内容都要进行修改的情况&#xff0c;在不支持列模式的编辑器中&#xff0c;可能需要用户逐行去编辑&#xff0c;比如有下面一段扯淡文本&#xff1a; ADD NRNFREQ:LOCA…

论文笔记(六十三)Understanding Diffusion Models: A Unified Perspective(一)

Understanding Diffusion Models: A Unified Perspective&#xff08;一&#xff09; 文章概括引言&#xff1a;生成模型背景&#xff1a;ELBO、VAE 和分层 VAE证据下界&#xff08;Evidence Lower Bound&#xff09;变分自编码器 &#xff08;Variational Autoencoders&#x…

【重庆市乡镇界】面图层shp格式arcgis数据乡镇名称和编码wgs84坐标无偏移内容测评

标题中的“最新重庆市乡镇界面图层shp格式arcgis数据乡镇名称和编码wgs84坐标无偏移最新”指的是一个地理信息系统&#xff08;GIS&#xff09;的数据集&#xff0c;特别设计用于ArcGIS软件。这个数据集包含了重庆市所有乡镇的边界信息&#xff0c;以Shapefile&#xff08;.shp…

【0x04】HCI_Connection_Request事件详解

目录 一、事件概述 二、事件格式及参数 2.1. HCI_Connection_Request 事件格式 2.2. BD_ADDR 2.3. Class_Of_Device 2.4. Link_Type 三、主机响应 3.1. ACL链接类型 3.2. SCO或eSCO链接类型 四、应用场景 4.1. 设备配对场景 4.2. 蓝牙文件传输场景 4.3. 蓝牙物联网…