Lucene8 Group操作

/**
 * 根据指定的查询条件和分组字段执行分组搜索。
 *
 * @param query 查询条件
 * @param groupField 分组字段,一般为类型等字段,按照类型分组
 * @param resultType 结果类型:
 *                   "totalHits" 表示返回每个分组的文档总数,
 *                   "fieldValue" 表示返回每个分组的指定字段值列表,如返回分组对应的企业名称或者id值。
 * @param resultField 当 resultType 为 "fieldValue" 时,此参数指定要返回的字段名称
 * @return 包含分组结果的 Map,键为分组值,值为总命中数或字段值列表
 * @throws IOException 如果在搜索过程中发生 I/O 错误
 */
public Map<String, Object> groupSearch(Query query, String groupField, String resultType , String resultField) throws IOException {

    GroupingSearch groupingSearch = new GroupingSearch(groupField);
    groupingSearch.setCachingInMB(1000.0, true);
    groupingSearch.setAllGroups(true);
    groupingSearch.setGroupDocsLimit(10);

    Map<String, Object> groupResult = new HashMap<>();

    TopGroups<BytesRef> searchResult = groupingSearch.search(luceneIndex.getIndexSearcher(), query, 0, 1000);

    for (GroupDocs<BytesRef> item : searchResult.groups)
    {
        if (item.groupValue  != null)
        {
            if ("fieldValue".equals(resultType) && StringUtil.isEmpty(resultField))
            {
                List<String> groupsFieldResult = new ArrayList<>();
                for (ScoreDoc scoreDoc : item.scoreDocs)
                {
                    Document doc = luceneIndex.getIndexSearcher().doc(scoreDoc.doc);
                    groupsFieldResult.add(doc.get(resultField));
                }
                groupResult.put(item.groupValue.utf8ToString(), groupsFieldResult);

            }
            else
            {
                groupResult.put(item.groupValue.utf8ToString(), item.totalHits.value);

            }
        }
    }
    return groupResult;
}
  • 5
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值