gpt4 book ai didi

java - ElasticSearch Java API 从查询生成器获取不同的值

转载 作者:行者123 更新时间:2023-12-02 11:03:46 25 4
gpt4 key购买 nike

我使用 Java API 查询 ElasticSearch 并收到大量重复值。我只想从查询中获取唯一值(不同值)。我们如何从查询生成器中获取不同的值。

请在下面找到我的 java 代码,它给出了重复的值。

QueryBuilder qb2=null;
List<Integer> link_id_array=new ArrayList<Integer>();
for(Replacement link_id:linkIDList) {
link_id_array.add(link_id.getLink_id());
}

qb2 = QueryBuilders.boolQuery()
.must(QueryBuilders.termsQuery("id", link_id_array));

正在使用带有 RestHighLevelClient 的 Elasticsearch 6.2.3 版本

最佳答案

方式一:需要使用所谓的聚合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();

关于java - ElasticSearch Java API 从查询生成器获取不同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51138501/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com