How to Sort by Count

Hi Ross,

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.

Let me know if you have any questions about this.

Cory