Reverse data from Fauna DB

642 Views Asked by At

I have been looking at the docs indexes for FQL and Fauna DB. Is there a way to reverse the order of the data returned from the query?

Here is the code I have:

q.Map(
  q.Paginate(q.Match(q.Index("all_pages")), {
    //! Find way to change order
    size: 3
  }),
  ref => q.Get(ref)
)

The docs mention the reverse flag.

Does anyone know how to use it?

3

There are 3 best solutions below

3
Brecht De Rooms On

Imagine you have a collection that contains documents with a price field, let's call it ... ermm ... priceables!

Let's add two documents to the collection with price 1 and price 2.

[{
  "price": 1
},
{
  "price": 2
}]

Image in UI console of the documents

Create a regular index

Create a regular range index on that price value with the following snippet:

CreateIndex({
  name: "regular-value-index",
  unique: false,
  serialized: true,
  source: Collection("priceables"),
  terms: [],
  values: [
    {
      field: ["data", "price"]
    }
  ]
})

Create a reverse index

There can be multiple values (e.g. a composite index) and the reverse field can be set per value. To create a reverse index, set reverse to true for that specific value.

CreateIndex({
  name: "reverse-value-index",
  unique: false,
  serialized: true,
  source: Collection("priceables"),
  terms: [],
  values: [
    {
      field: ["data", "price"],
      reverse: true
    }
  ]
})

If you go to the UI console and open the index you will notice the values are sorted from highest to low. UI console, reverse index

I assume that what confused you is that you can't set the reverse boolean in the UI yet. But you can just go to Shell and paste in the FQL code to create the index: Image of the shell

0
WΔ_ On

I just reversed an Index successfully. The docs are helpful, but they don't give an example where the Map function is implemented. The secret is to wrap the Map function as well, with q.Reverse:

q.Reverse(
 q.Map(
  q.Paginate(q.Match(q.Index("all_pages")), {
    //! Find way to change order
    size: 3
  }),
  ref => q.Get(ref)
 )
)

This should work for you!

0
eskwayrd On

The best way to reverse the order of data is to use an index, per Brecht's answer. Fauna stores index entries in sorted order, so when your index uses reverse: true matching entries from the index are already sorted in reverse order.

WΔ_'s answer is technically correct, but probably not what you want. Using Reverse around a Paginate reverses the items in the page, but not the overall set. Suppose your set was the letters of the alphabet, and your page size is 3. Without Reverse, you'd expect to see pages with ABC, DEF, etc. If you're trying to change the order of the set, you'd expect to see ZYX, WVU, etc. WΔ_'s answer results in CBA, FED, etc.

Reverse can operate on a set. So you can Reverse(Match(Index("all_pages"))), and Paginate/Map that result. Note that for large sets, your query might fail since Reverse has to operate on the entire set.