Search code examples
indexingfaunadb

Is there a way to sort documents by an integer using faunaDB?


Is there a way to sort documents by an integer with indexes using faunaDB? I have multiple documents with data.likes, which is an integer. Is it possible to simply get the documents by most likes sorted first, and the least sorted last? Thanks in advance


Solution

  • Yes.

    To do this, make sure that your index includes the likes field in the values definition. If you specify reverse: true for that field, you'll see the results sorted in descending order.

    For example:

    CreateIndex({
      name: 'popular-pets',
      source: Collection('pets'),
      values: [
        { field: ["data", "likes"], reverse: true },
        { field: ["ref"] },
      ],
    })
    

    Then you can do this:

    Map(
      Paginate(Match(Index("popular-pets"))),
      Lambda(["likes", "ref"], Get(Var("ref")))
    )