索引中获得不同的值

索引中获得不同的值

当前,我正在使用这段代码,该代码是我从字段获取值而编写的:

QueryBuilder qb = QueryBuilders.matchPhrasePrefixQuery("tagName", "june");
            SearchResponse response = esclient.prepareSearch(index).setTypes(type)
                    .setQuery(qb)
                    .execute().actionGet();

            SearchHit[] hits = response.getHits().getHits();
            System.out.println(hits.length);

            for (SearchHit hit : hits) {
                Map map = hit.getSource();
                System.out.println((String) map.get("tagName"));
                strings.add((String) map.get("tagName"));
            }

但是,是否有其他方法可以从索引中获得不同的值?
还是可以修改以上内容?

最佳答案

您可以使用terms aggregation

这要求不对该字段进行分析。

    public static List<String> getDistinctAgg(TransportClient client, String indexName, String fieldName, int requiredSize) {
    List<String> values = new LinkedList<>();

    try {


        TermsAggregationBuilder aggregationBuilder = new TermsAggregationBuilder(fieldName + "_Agg", ValueType.STRING);
        aggregationBuilder.field(fieldName);
        aggregationBuilder.bucketCountThresholds(new TermsAggregator.BucketCountThresholds(1, 1, requiredSize, 5));

        QueryBuilder query = QueryBuilders.matchAllQuery();


        SearchResponse response = client.prepareSearch(indexName)
                .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
                .setQuery(query).addAggregation(aggregationBuilder).setSize(0).get();
        if (response == null) return null;

        StringTerms terms = ((StringTerms) response.getAggregations().get(fieldName + "_Agg"));

        if (terms != null) {

            List<Terms.Bucket> buckets = terms.getBuckets();
            if (buckets != null && buckets.size() > 0) {


                for (Terms.Bucket bucket : buckets) {
                    values.add(bucket.getKeyAsString());
                }
            }
            return values;
        }

    } catch (Exception e) {
        return null;
    }
    return null;
}

关于java - java:从elasticsearch索引中获得不同的值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48748439/

10-10 18:29