firegloves
firegloves

Reputation: 5709

How to specify from clause in Java Elasticsearch client during a bucket sort aggregation

I'm trying to implement pagination for a bucket sort aggregation. I have this working query:

GET /test/_search
{

  "query": {
    "bool": {
      "must": [
        { "match": { "code": 66 }}
      ]
    }
  },
    "aggs": {
      "group_by_user": {
        "terms": {
          "field": "userId.keyword"
        },
        "aggs": {
          "total_points": {
            "sum": {
              "field": "points"
            }
          },
          "test_bucket_sort": {
            "bucket_sort": {
              "sort": [
                {"total_points": {"order": "desc"}}
              ],
              "size": 3,
              "from": 1
            }
          }
        }
      }
    }
}

It is working and returning 3 aggregated records skipping the first. Now I'm trying to reproduce this query with Java API. I skip non-relevant code and I post only the "aggs" part:

       this.aggregationBuilder = AggregationBuilders
                .terms("group_by_user")
                .field("userId.keyword")
                .subAggregation(AggregationBuilders.sum("total_points").field("points"))
                .order(BucketOrder.aggregation("total_points", false))
                .size(5);

I can't find a way to specify from(1), anyone knows if it is not implemented in java API or if exists a workaround?

Upvotes: 1

Views: 990

Answers (1)

Val
Val

Reputation: 217554

That's a good start, however, you're not using the right code for the bucket_sort pipeline aggregation. Here is what you should do:

   List sort = Arrays.asList(new FieldSortBuilder("total_points").order(SortOrder.DESC));
   BucketSortPipelineAggregationBuilder bucketSort = PipelineAggregatorBuilders.bucketSort("test_bucket_sort", sort).from(1).size(3);

   this.aggregationBuilder = AggregationBuilders
            .terms("group_by_user")
            .field("userId.keyword")
            .subAggregation(AggregationBuilders.sum("total_points").field("points"))
            .subAggregation(bucketSort)

Upvotes: 8

Related Questions