I have 3 collections: User, Review, and Tag. A user authors reviews, and can optionally add tags to them (with suggested tags being offered by count; very similar to when I click to add a tag to this forum post for example, except only pulling from the author’s previous tags rather than globally)
So, somehow, I need to be able to query:
paginated tags by user, sorted by count
paginated tags by review, sorted in the order they were added to the review
paginated reviews by user by tag
All of the sort examples I’ve come across use indexes, so I’m already stuck at #1 since I’m not sure how to make an index sort work by count.
See below for a simplified version of my schema for reference (open to refactoring, if needed)
type User {
username: String!
reviews: [Review]
}
type Review {
user: User!
text: String!
tags: [Tag]
}
type Tag {
user: User!
text: String!
reviews: [Review]
}
This is similar to an earlier post in the forums, “SQL group by, having counterpart in FaunaDB”. Your case is complicated by wanting to sort on the count of the relationship, though. That’s hard to do, because FQL depends on indexes to handle sorting. There’s not a Sort() function that can be called; sorting is always handled by either _asc or _desc prepended to the name of an index.
This is because of the nature of Fauna and, especially, how billing is handled. Since you’re charged on a per operation basis, hiding operations in temporary tables (like what would be needed to allow for a sorting function) would just cause confusion over the billing. It’s better to be upfront about those costs, and allow you to decide on the tradeoffs needed for your particular application.
In this case, to accomplish sorting by count of tags, you would want to add a new type to your schema:
type TagCount {
user: User!
tag: Tag!
count: Int!
}
Then you could add an index that will sort by the count element. You would also want to build a UDF that would increment the count every time a tag is added.
I have to correct something I said in my previous post: indexes are not sorted based on their name, they default to sorting in ascending order and using reverse: true in the values will cause them to sort in descending order. Sorry for the mixup and any confusion.