0

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.

Aaron Austin
  • 225
  • 1
  • 2
  • 9

1 Answers1

2

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
})
Marrony
  • 231
  • 1
  • 3
  • Thanks! I tried it out with your code and it worked. It also worked with `after` as `["2019-12-15", Ref(Collection("posts"), "RefIDString)]. Are you saying that the ref is not necessary? Since the dates in my db are just strings and not unique, I assumed it needed the ref as well. Also, I don't really need the date returned in my index, but I do want it to sort based on the date. I'm just using the ref to grab the document. Is there a way to set up the index with a sort on the date and only return the ref? I couldn't find a way. Thanks for the help. – Aaron Austin Jul 23 '20 at 17:08
  • The index cursors use lexicographic order, so the next element is only compared if the previous is equal and so on. Unfortunately you need to return the date in the index in order to sort it, even if you don't need the value. – Marrony Jul 23 '20 at 17:29