目前我正在使用我编写的代码来获取字段中的值:
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"));
}
但是有没有从索引中获取不同值的替代方法? 或者可以修改以上内容吗?
答案 0 :(得分:1)
您可以使用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;
}