Sort by specific value with a limit

Hi there,

Sorry if this has been asked already…

I want to sort an entire collection (called “likes”) by the like count and get the top 25 results.

The only data I am interested in is the “name” and the “likeCount” for each item in my collection.

For context I am writing a Vue.js application, and want to output a list of the top 25 most liked items.

Currently I am just requesting ALL items and filtering it out through JavaScript afterwards, which isn’t ideal and uses more read requests on my account (I think?)

Any suggestions would be greatly appreciated!

Here’s my current query to get all items, which I want to change to something more efficient if possible:

    let query = await client.query(
        q.Paginate(q.Documents(q.Collection('likes')), {
          after: 1,
          size: 500,
        q.Lambda((show) => q.Get(show))


Hi @Monty9120 ,

Sorting in Fauna is accomplished using indexes, specifically by ordering of an index’s values . The values field in an index defines one or more fields that are returned in the result set, and the fields can be in ascending or descending order.

For example, I would create an index on thelikes collection to sort based on the likeCount

  name: "likes_sort_by_likeCount",
  source: Collection("likes"),
    {field:["data","likeCount"], reverse:true},
    {field: ["data","name"]}

I am defining the fields that you want in your result set (name and likeCount) as values of the index and specifying that likeCount is sorted in descending order.

There are more detailed examples of sorting with indexes in the documentation

Then, to query for the top 25 results from the index, Paginate can be used with the size parameter set to 25.



Thank you! This makes a lot of sense and matches up with some the tests I did yesterday

Have a great day/night :slight_smile:

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