Aaron Austin
Aaron Austin

Reputation: 225

How do I paginate a sorted index in Fauna DB?

I've created an index to sort blog posts by a date. However, when I try to paginate the results, it keeps returning the initial results.

Here's my index:

CreateIndex({
  name: "posts_desc",
  unique: false,
  serialized: true,
  source: Collection("posts"),
  terms: [],
  values: [
    {
      field: ["data", "sort_date"],
      reverse: true
    },
    {
      field: ["ref"]
    }
  ]
}

Then I map out results to get each document by the ref.

Map(
  Paginate(Match(Index("posts_desc")), {
    after: [Ref(Collection("posts"), "Ref ID for 6th Document")],
    size: 5
  }),
  Lambda(["date", "ref"], Get(Var("ref")))
)

After running this whether in my code or via the Fauna shell, I still get the first 5 results. I had all this working with the original index (all_posts) but now it doesn't seem to be working. Also, the after object that's returned now has my sort_date value in the first position of the array and the ref in the second position. I tried moving the ref to the first position in my index, but that broke the sorting. Any help appreciated.

Upvotes: 0

Views: 916

Answers (1)

Marrony
Marrony

Reputation: 231

Your index return tuples of [sort_date, ref], so your after cursor should respect those values, you should create a cursor where the first element is a date, and optionally a ref on the second value, ie:

Paginate(Match(Index("posts_desc")), {
  after: [Date("2020-07-23")],
  size: 5
})

Upvotes: 2

Related Questions