Python 官方文档:入门教程 => 点击学习
通过聚合查询获取group by 后的数量 public static int geTKEyCount(String key, String index) {
public static int geTKEyCount(String key, String index) {
int count = 0;
TransportClient client = null;
try {
client = connectionPool.getConnection();
if (client == null) {
throw new Exception("没有获取到连接!");
}
SearchRequestBuilder search = client.prepareSearch(index);
//cardinality聚合查询,相当于groupby字段名
SearchResponse sr = search.addAggregation(AggregationBuilders.cardinality(key + "_count").field(key)).execute().actionGet();
//从返回数据提取id总数
Cardinality result = sr.getAggregations().get(key + "_count");
long value = result.getValue();
count = (int) value;
} catch (InterruptedException e) {
} catch (Exception e) {
logger.error("getKeyCount错误", e);
} finally {
connectionPool.releaseConnection(client);
}
return count;
}
public static List<String> getAllKey(String key, String index) {
int keyCount = getKeyCount(key, index);
List<String> strings = new ArrayList<>();
TransportClient client = null;
try {
client = connectionPool.getConnection();
if (client == null) {
throw new Exception("没有获取到数据库连接!");
}
SearchRequestBuilder searchRequestBuilder = client.prepareSearch(index);
//使用聚合,实现去重查询
SearchResponse searchResponse = searchRequestBuilder.
addAggregation(AggregationBuilders.terms("models").field(key).size(keyCount)).execute().actionGet();
Terms term = searchResponse.getAggregations().get("models");
List<? extends Terms.Bucket> buckets = term.getBuckets();
//遍历结果,提取出id
for (Terms.Bucket bucket : buckets) {
String keyAsString = bucket.getKeyAsString();
strings.add(keyAsString);
}
buckets.clear();
} catch (InterruptedException e) {
} catch (Exception e) {
logger.error("getAllKey错误", e);
} finally {
connectionPool.releaseConnection(client);
}
return strings;
}
到此这篇关于Java通过聚合查询获取group by 后的数量的文章就介绍到这了,更多相关Java 聚合查询获取group by数量内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
--结束END--
本文标题: java通过聚合查询实现elasticsearch的groupby后的数量
本文链接: https://www.lsjlt.com/news/161040.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0