欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java 通过聚合查询实现elasticsearch的group by后的数量

程序员文章站 2022-03-06 13:27:08
通过聚合查询获取group by 后的数量/** * 获取key的个数 * * @param key 要group by的字段名 * @param index 索引...

通过聚合查询获取group by 后的数量

/**
     * 获取key的个数
     *
     * @param key   要group by的字段名
     * @param index 索引名称
     * @return id的个数
     */
    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;
    }

获取group by后的所有key值

/**
     * 获取所有key
     *
     * @param key   被group by的字段名
     * @param index 索引名称
     * @return 所有id
     */
    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数量内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!