Hello all,
This case mainly talks about "Elasticsearch aggregation query returns all"
When Elasticsearch queries, some queries cannot meet our requirements. In this case, we use the aggregation function of Elasticsearch. The following describes how to use aggregation.
Elasticsearch performs aggregation query:
{
"from": 0,
"size": 10,
"aggregations": {
"types": {
"terms": {
"field": "types"
}
}
}
}
Java API :
AggregationBuilder<?> aggregation = AggregationBuilders.terms("types").field("types");
SearchRequestBuilder srb = client.prepareSearch(BaseMapping.index);
srb.setSearchType(SearchType.DFS_QUERY_THEN_FETCH);
SearchResponse response = srb.execute().actionGet();
Aggregations agg = response.getAggregations();
Terms types = agg.get("types");
In this way, aggregated data can be obtained. Aggregate query by field type. In this case, 10 aggregated data records are returned. But I want to go back to all of them?
I looked at the source code, personally feel more pit.
/**
* Sets the size - indicating how many term buckets should be returned (defaults to 10)
*/
public TermsBuilder size(int size) {
bucketCountThresholds.setRequiredSize(size);
return this;
}
The number of returned records can be specified by adding size. The default value is 10. But it doesn't say, I want the size(0) of all the data.
Later, I found no relevant information. I asked other students to try size(-1) or size(0). As a result, I think the probability of -1 is higher, and an error is reported. According to the error, the size must be greater than or equal to 0. Try 0. The result returns all, which is Global. The following formula is obtained.
{
"from": 0,
"size": 10,
"aggregations": {
"types": {
"terms": {
"field": "types",
"size": 0
}
}
}
}
Java API:
//Set a type aggregation field. The aggregation field is types (multiple fields are allowed), and size = 0 indicates global.
AggregationBuilder<?> aggregation = AggregationBuilders.terms("types").field("types").size(0);
SearchRequestBuilder srb = client.prepareSearch(BaseMapping.index);
srb.setSearchType(SearchType.DFS_QUERY_THEN_FETCH);
SearchResponse response = srb.execute().actionGet();
Aggregations agg = response.getAggregations();
//Obtain aggregated data.
Terms types = agg.get("types");
That's all, thanks!