java 如何加快返回唯一的ElasticSearch值?

dgsult0t  于 2023-01-19  发布在  Java
关注(0)|答案(1)|浏览(92)

我有超过100个索引在弹性。我想返回所有索引的所有唯一值。

String[] instanceNames = getAllIndices().toArray(String[]::new);
    Map<String, Map<String, Set<String>>> results = new HashMap<>();

    for (String element : instanceNames) {

        SearchRequest searchRequest = new SearchRequest();
        searchRequest.indices(element);
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.matchAllQuery);
        searchSourceBuilder.aggregation(AggregationBuilders.terms("DISTINCT_VALUES").field("provider.keyword"));
        searchRequest.source(searchSourceBuilder);
        SearchResponse searchResponse = null;
        try {
            searchResponse = getClient().search(searchRequest, RequestOptions.DEFAULT);
        } catch (ElasticsearchException | IOException e) {
            throw new ServiceException(I18n.ELASTIC_SEARCH_ERROR, e);
        }

        List<SearchHit> searchHits = Arrays.asList(searchResponse.getHits().getHits());
        }

instanceNames -〉包含了我的elasticsearch中的所有索引。这个方法可以工作,但是返回数据非常慢。

jm2pwxwz

jm2pwxwz1#

好了,我解决了这个问题。我用AggregationBuilders创建了两个聚合。第一个是索引,第二个是提供者。

SearchRequest searchRequest = new SearchRequest();
    searchRequest.indices("_all");
    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    searchSourceBuilder.query(QueryBuilders.matchAllQuery()).size(0);
    searchSourceBuilder.aggregation(AggregationBuilders.terms(aggregationIndexName)
            .field("_index")
            .size(100)
            .subAggregation(AggregationBuilders.terms(aggregationProviderName)
                    .field("provider.keyword")
                    .size(100)));
    searchRequest.source(searchSourceBuilder);

相关问题