java代码实现es索引合并

可以根据es的高级查询获取所有的索引,然后可以根据索引的创建时间和数据条数等条件做出筛选
 

 public List<String> getFilterIndex(String index, Long count) throws IOException {
        // 定义存储索引的列表
        List<String> indexList;
        // 创建一个SearchRequest对象,指定要查询的索引名和查询条件
        GetAliasesRequest request = new GetAliasesRequest().indices("*");
        //获取响应结果
        GetAliasesResponse alias = elasticsearchFactory.getClient().indices().getAlias(request, RequestOptions.DEFAULT);
        //获取所有索引根据条件筛选下索引
        indexList = alias.getAliases().keySet().stream().filter(i -> org.springframework.util.StringUtils.hasText(index) ? i.contains(index) : true).filter(i -> i.contains("_")).filter(i -> !i.contains(mergedIndex)).collect(Collectors.toList());
        // 获取当前时间戳
        Instant currentInstant = Instant.now();
        // 计算一周前的时间戳
        Instant oneWeekAgoInstant = currentInstant.minus(7, ChronoUnit.DAYS);
        long oneWeekAgoTimeStamp = oneWeekAgoInstant.toEpochMilli();
        //根据索引的生成时间和索引的数量进行筛选
        List<String> newIndex = indexList.stream().filter(bean -> {
            SearchRequest searchRequest = new SearchRequest(bean);
            SearchSourceBuilder builder = new SearchSourceBuilder();
            builder.query(QueryBuilders.matchAllQuery());
            searchRequest.source(builder);
            try {
                SearchResponse response = elasticsearchFactory.getClient().search(searchRequest, RequestOptions.DEFAULT);
                //获取索引详情
                GetIndexRequest requestDetail = new GetIndexRequest(bean);
                GetIndexResponse responseDetail = elasticsearchFactory.getClient().indices().get(requestDetail, RequestOptions.DEFAULT);
                Long totalHits = response.getHits().getTotalHits().value;
                Map<String, Settings> indexSettings = responseDetail.getSettings();
                Settings settings = indexSettings.get(bean);
                //获取索引创建时间
                String creationDate = settings.get("index.creation_date");
                if (count != null && count > 0) {
                    return totalHits < count && oneWeekAgoTimeStamp > Long.parseLong(creationDate);
                } else {
                    return oneWeekAgoTimeStamp > Long.parseLong(creationDate);
                }
            } catch (IOException e) {
                throw new SdkException(e.getMessage());
            }
        }).collect(Collectors.toList());
        return newIndex;
    }

以上是根据条件获取的索引,会返回一个list集合
然后根据现有的索引去进行索引合并
 

 public void mergeIndex(List<String> mergeIndices) {
        // 查询处理需要合并的索引名唯一索引
        Set<String> uniqueMerges = mergeIndices.stream().map(bean -> bean.substring(0, bean.lastIndexOf("_"))).collect(Collectors.toSet());
        // 遍历唯一索引中index中筛选出需要合并的索引名
        uniqueMerges.forEach(indexMerge -> {
            // 筛选需要合并的索引数量
            List<String> list = mergeIndices.stream().filter(bean -> bean.contains(indexMerge)).collect(Collectors.toList());
            // 如果需要合并的索引数量大于1需要进行索引操作
            if (list.size() > 1) {
                list.forEach(dataIndex -> {
                    try {
                        ReindexRequest reindexRequest = new ReindexRequest(); // 创建重新索引请求对象
                        reindexRequest.setSourceIndices(dataIndex); // 设置源索引,即需要合并的索引名称
                        reindexRequest.setDestIndex(indexMerge + mergedIndex); // 设置目标索引,即合并后的索引名称
                        reindexRequest.setConflicts("proceed"); // 设置冲突处理策略,"proceed"表示忽略冲突
                        SearchRequest searchRequest = new SearchRequest(dataIndex); // 创建搜索请求对象,用于搜索需要合并的索引
                        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); // 创建搜索源构建器
                        sourceBuilder.query(QueryBuilders.matchAllQuery()); // 添加查询条件,这里使用MatchAllQuery匹配所有文档
                        searchRequest.source(sourceBuilder); // 将搜索源构建器添加到搜索请求中
                        SearchResponse searchResponse = elasticsearchFactory.getClient().search(searchRequest, RequestOptions.DEFAULT); // 执行搜索请求,获取搜索响应对象
                        BulkRequest bulkRequest = new BulkRequest(); // 创建批量请求对象
                        searchResponse.getHits().forEach(hit -> { // 遍历搜索响应中的所有命中文档
                            IndexRequest indexRequest = new IndexRequest(indexMerge + mergedIndex).source(hit.getSourceAsString(), XContentType.JSON); // 创建索引请求对象,并将该文档添加到请求中
                            bulkRequest.add(indexRequest); // 将索引请求对象添加到批量请求中
                        });
                        BulkResponse bulkResponse = elasticsearchFactory.getClient().bulk(bulkRequest, RequestOptions.DEFAULT); // 执行批量请求,获取批量响应对象
                        if (bulkResponse.hasFailures()) { // 判断批量响应是否有错误
                            logger.error("Failed to merge indices: {}", bulkResponse.buildFailureMessage()); // 如果有错误,记录日志并输出错误信息
                        } else {
                            logger.info("Merged indices successfully"); // 如果没有错误,记录日志表示索引合并成功
                            DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest(dataIndex); // 创建删除索引请求对象
                            elasticsearchFactory.getClient().indices().delete(deleteIndexRequest, RequestOptions.DEFAULT); // 执行删除索引请求
                        }
                    } catch (IOException e) {
                        logger.info("===============数据合并索引失败=============={}", e.getMessage());
                        throw new SdkException(ResultEnum.FAIL.message());
                    }
                });
            }
        });
    }

还可以根据更多筛选条件实现请自行扩展

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值