Collect first document from each bucket

Hi,

I need some help with a query:

I have a "students" index, and each student has a "classroomId" and a "grade" fields.

I need to get the best student in each class.

I'm using "aggs", but what I get is the list of all students, and in the aggregations section, the number of students of each class.

Maybe "aggs" is not designed for this purpose. Whay I need to use instead of it?

Regards

This is impossible to answer without a concrete example that includes index creation, index mapping, sample documents and the query you have been tested with. Without those everything else would be just trying to guess things. See https://www.elastic.co/help

Also being more exact what the best student is would help. The one where the sum of all grades is the highest? The one with the single highest grade? Hard to tell until now

Sorry, my fault. I 've an insane clear schema on my mind and I don't think in external points of view.

I get the solution, so I post here:

    {
        "aggs" : {
            "classroom_agg" : {
                "terms" : { 
                    "field" : "classRoomId"
                },
                "aggs": {
                    "best_student": {
                        "top_hits": {
                            "size": 1,
                            "sort": [
                                {
                                    "grade": {
                                        "order": "desc"
                                    }
                                }
                            ]
                        }
                    }   
                }
            }
        }
    }

What I missed in my first attempts was the 'top_hits' sections. I didn't know about this query term, and I was becoming crazy.

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.