java使用elasticsearch分组进行聚合查询(group by)-项目中实际应用
java连接elasticsearch 进行聚合查询进行相应操作
一:对单个字段进行分组求和
1、表结构图片:

根据任务id分组,分别统计出每个任务id下有多少个文字标题
1.SQL:select id, count(*) as sum from task group by taskid;
java ES连接工具类
public class ESClientConnectionUtil {
public static TransportClient client=null;
public final static String HOST = "192.168.200.211"; //服务器部署
public final static Integer PORT = 9301; //端口
public static TransportClient getESClient(){
System.setProperty("es.set.netty.runtime.available.processors", "false");
if (client == null) {
synchronized (ESClientConnectionUtil.class) {
try {
//设置集群名称
Settings settings = Settings.builder().put("cluster.name", "es5").put("client.transport.sniff", true).build();
//创建client
client = new PreBuiltTransportClient(settings).addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(HOST), PORT));
} catch (Exception ex) {
ex.printStackTrace();
System.out.println(ex.getMessage());
}
}
}
return client;
}
public static TransportClient getESClientConnection(){
if (client == null) {
System.setProperty("es.set.netty.runtime.available.processors", "false");
try {
//设置集群名称
Settings settings = Settings.builder().put("cluster.name", "es5").put("client.transport.sniff", true).build();
//创建client
client = new PreBuiltTransportClient(settings).addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(HOST), PORT));
} catch (Exception ex) {
ex.printStackTrace();
System.out.println(ex.getMessage());
}
}
return client;
}
//判断索引是否存在
public static boolean judgeIndex(String index){
client= getESClientConnection();
IndicesAdminClient adminClient;
//查询索引是否存在
adminClient= client.admin().indices();
IndicesExistsRequest request = new IndicesExistsRequest(index);
IndicesExistsResponse responses = adminClient.exists(request).actionGet();
if (responses.isExists()) {
return true;
}
return false;
}
}
java ES语句(根据单列进行分组求和)
//根据 任务id分组进行求和
SearchRequestBuilder sbuilder = client.prepareSearch("hottopic").setTypes("hot");
//根据taskid进行分组统计,统计出的列别名叫sum
TermsAggregationBuilder termsBuilder = AggregationBuilders.terms("sum").field("taskid");
sbuilder.addAggregation(termsBuilder);
SearchResponse responses= sbuilder.execute().actionGet();
//得到这个分组的数据集合
Terms terms = responses.getAggregations().get("sum");
List<BsKnowledgeInfoDTO> lists = new ArrayList<>();
for(int i=0;i<terms.getBuckets().size();i++){
//statistics
String id =terms.getBuckets().get(i).getKey().toString();//id
Long sum =terms.getBuckets().get(i).getDocCount();//数量
System.out.println("=="+terms.getBuckets().get(i).getDocCount()+"------"+terms.getBuckets().get(i).getKey());
}
//分别打印出统计的数量和id值
根据多列进行分组求和
//根据 任务id分组进行求和
SearchRequestBuilder sbuilder = client.prepareSearch("hottopic").setTypes("hot");
//根据taskid进行分组统计,统计出的列别名叫sum
TermsAggregationBuilder termsBuilder = AggregationBuilders.terms("sum").field("taskid");
//根据第二个字段进行分组
TermsAggregationBuilder aAggregationBuilder2 = AggregationBuilders.terms("region_count").field("birthplace");
//如果存在第三个,以此类推;
sbuilder.addAggregation(termsBuilder.subAggregation(aAggregationBuilder2));
SearchResponse responses= sbuilder.execute().actionGet();
//得到这个分组的数据集合
Terms terms = responses.getAggregations().get("sum");
List<BsKnowledgeInfoDTO> lists = new ArrayList<>();
for(int i=0;i<terms.getBuckets().size();i++){
//statistics
String id =terms.getBuckets().get(i).getKey().toString();//id
Long sum =terms.getBuckets().get(i).getDocCount();//数量
System.out.println("=="+terms.getBuckets().get(i).getDocCount()+"------"+terms.getBuckets().get(i).getKey());
}
//分别打印出统计的数量和id值
对多个field求max/min/sum/avg
SearchRequestBuilder requestBuilder = client.prepareSearch("hottopic").setTypes("hot");
//根据taskid进行分组统计,统计别名为sum
TermsAggregationBuilder aggregationBuilder1 = AggregationBuilders.terms("sum").field("taskid")
//根据tasktatileid进行升序排列
.order(Order.aggregation("tasktatileid", true));
// 求tasktitleid 进行求平均数 别名为avg_title
AggregationBuilder aggregationBuilder2 = AggregationBuilders.avg("avg_title").field("tasktitleid");
//
AggregationBuilder aggregationBuilder3 = AggregationBuilders.sum("sum_taskid").field("taskid");
requestBuilder.addAggregation(aggregationBuilder1.subAggregation(aggregationBuilder2).subAggregation(aggregationBuilder3));
SearchResponse response = requestBuilder.execute().actionGet();
Terms aggregation = response.getAggregations().get("sum");
Avg terms2 = null;
Sum term3 = null;
for (Terms.Bucket bucket : aggregation.getBuckets()) {
terms2 = bucket.getAggregations().get("avg_title"); // org.elasticsearch.search.aggregations.metrics.avg.InternalAvg
term3 = bucket.getAggregations().get("sum_taskid"); // org.elasticsearch.search.aggregations.metrics.sum.InternalSum
System.out.println("编号=" + bucket.getKey() + ";平均=" + terms2.getValue() + ";总=" + term3.getValue());
}
如上内容若有不恰当支持,请各位多多包涵并进行点评。技术在于沟通!
java使用elasticsearch分组进行聚合查询(group by)-项目中实际应用的更多相关文章
- java使用elasticsearch进行模糊查询-已在项目中实际应用
java使用elasticsearch进行模糊查询 使用环境上篇文章本人已书写过,需要maven坐标,ES连接工具类的请看上一篇文章,以下是内容是笔者在真实项目中运用总结而产生,并写的是主要方法和思路 ...
- Mysql教程:(二)分组与函数查询group by
分组与函数查询 温馨提示:分组之后查询其他函数结果是不正确的: 分组函数:group by 按班级分组,查询出每班数学最高分:select class,max(maths) from score gr ...
- mqtt协议实现 java服务端推送功能(三)项目中给多个用户推送功能
接着上一篇说,上一篇的TOPIC是写死的,然而在实际项目中要给不同用户 也就是不同的topic进行推送 所以要写活 package com.fh.controller.information.push ...
- java 项目中几种O实体类的概念
经常会接触到vo,do,dto的概念,本文从领域建模中的实体划分和项目中的实际应用情况两个角度,对这几个概念进行简析. 得出的主要结论是:在项目应用中,vo对应于页面上需要显示的数据(表单),do对应 ...
- MongoDB分组查询,聚合查询,以及复杂查询
准备数据 from pymongo import MongoClient import datetime client=MongoClient('mongodb://localhost:27017') ...
- Django-model聚合查询与分组查询
Django-model聚合查询与分组查询 聚合函数包含:SUM AVG MIN MAX COUNT 聚合函数可以单独使用,不一定要和分组配合使用:不过聚合函数一般和group by 搭配使用 agg ...
- 使用Java操作Elasticsearch(Elasticsearch的java api使用)
1.Elasticsearch是基于Lucene开发的一个分布式全文检索框架,向Elasticsearch中存储和从Elasticsearch中查询,格式是json. 索引index,相当于数据库中的 ...
- MongoDB聚合查询及Python连接MongoDB操作
今日内容概要 聚合查询 Python操作MongoDB 第三方可视化视图工具 今日内容详细 聚合查询 Python操作MongoDB 数据准备 from pymongo import MongoCli ...
- JAVA项目中的常用的异常处理情况总结
可能遇见的异常或错误: 检查性异常:最具代表的检查性异常是用户错误或问题引起的异常,这是程序员无法预见的.例如要打开一个不存在文件时,一个异常就发生了,这些异常在编译时不能被简单地忽略. 运行时异常: ...
随机推荐
- UVA 11582 Colossal Fibonacci Numbers!(循环节打表+幂取模)
题目链接:https://cn.vjudge.net/problem/UVA-11582 /* 问题 输入a,b,n(0<a,b<2^64(a and bwill not both be ...
- DataGridView列标题(列标头)不能居中的解决方法
winform DataGridView列标题(列标头)不能完全居中的解决方法,一般列标题的居中我们都使用 DgvDemo.ColumnHeadersDefaultCellStyle.Alignmen ...
- @Html.Raw() 与Newtonsoft.Json.JsonConvert.SerializeObject()
一.后台 ViewBag.TypeList = typeList; 二.前台C# @{ var typeListFirst = ViewBag.TypeList;} 三.前台js中 var t ...
- PCA算法Python实现
源代码: #-*- coding: UTF-8 -*- from numpy import * import numpy def pca(X,CRate): #矩阵X每行是一个样本 #对样本矩阵进行中 ...
- QYH练字
汉字书写笔划,提取自百度汉语等网站... 以下凑字数: [发文说明]博客园是面向开发者的知识分享社区,不允许发布任何推广.广告.政治方面的内容.博客园首页(即网站首页)只能发布原创的.高质量的.能让读 ...
- 过滤器模式(Filter Pattern)
过滤器模式 一.什么是过滤器模式 过滤器模式(Filter Pattern),这种模式允许开发人员使用不同的标准来过滤一组对象,通过逻辑运算以解耦的方式把它们连接起来.这种类型的设计模式属于结构型 ...
- 如何解决VMware 虚拟机不能铺满屏幕
出现这种情况是因为分辨率设置问题,调整分辨率总能达到你想要的效果: 首先设置vmware为全屏模式 查看物理机的分辨率,然后再将虚拟机的分辨率设置了跟物理机的一致.完美解决 windows10查看分辨 ...
- Django Rest framework 之 视图
RESTful 规范 django rest framework 之 认证(一) django rest framework 之 权限(二) django rest framework 之 节流(三) ...
- linux下将本地文件上传到github中?
今天编写一份Python基础代码,经过Linux上传到github上,遇到点问题,已经解决 1.首先sudo su 进入root 用户 2.ls 检查出当前文件下有什么文件 3. cd 进入你将要上传 ...
- 【读书笔记】iOS-自动布局
自动布局是一项强大的功能,它允许开发者创建一个单一的用户界面,它会自动调整屏幕大小,方向和本地化,Xcode5中的编辑界面的自动布局功能已经大大增强了.当约束缺失或错误配置时,界面生成器可以修复布局. ...