我正在使用Java API查询ElasticSearch,并且获得了大量重复值。我只想从查询中获得唯一值(唯一值)。我们如何从查询生成器中获得不同的值。
请在下面找到我的Java代码,该代码给出重复的值。
dbClearResult()
Am使用带有RestHighLevelClient的弹性搜索6.2.3版本
答案 0 :(得分:0)
方法1:您需要使用所谓的汇总API:
示例查询以获取不同的电子邮件客户端:
{
"query" : {
"match_all" : { }
},
"aggregations" : {
"label_agg" : {
"terms" : {
"field" : "Email_client",
"size" : 100
}
}
}
}
Java代码示例=>
SearchRequestBuilder aggregationQuery =
client.prepareSearch("emails")
.setQuery(QueryBuilders.matchAllQuery())
.addAggregation(AggregationBuilders.terms("label_agg")
.field("Email_client").size(100));
SearchResponse response = aggregationQuery.execute().get();
Aggregation aggregation = response.getAggregations().get("label_agg");
StringTerms st = (StringTerms) aggregation;
return st.getBuckets().stream()
.map(bucket -> bucket.getKeyAsString())
.collect(toList());
方式2: 使用聚合Api的基数: 弹性查询示例:
{
"size": 0,
"aggs": {
"distinct": {
"cardinality": {
"field": "Email_client",
"size" : 100
}
}
}
Java代码示例=>
AggregationBuilder agg11 = AggregationBuilders.cardinality("distinct").field("Email_client");
SearchResponse response11 = client.prepareSearch("emails")// we can give multiple index names here
.setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
.setQuery(query11)
.addAggregation(agg11)
.setExplain(true)
.setSize(0)
.get();