'Sanity CMS custom sorting

I don’t know if exists some way to sorting the results by custom field. My query:

 *[_type == "movies" && actors]
{
   ..., 
   isHarryMovie: name match "Harry*" 
}

So I want to sort the results by isHarry, is it posible?

I tried something like this:

 *[_type == "movies" && actors] | order(isHarryMovie asc)
{
   ..., 
   isHarryMovie: name == "Harry" 
}

and

 *[_type == "movies" && actors] | order("isHarryMovie" asc)
{
   ..., 
   isHarryMovie: name == "Harry" 
}

but they didn't work



Solution 1:[1]

You can order after projecting:

*[_type == "movies"] {
  ..., 
  isHarryMovie: name match "Harry*" 
} | order(isHarryMovie desc)

This will sort by the isHarryMovie attribute that you added to each document.

But this kind of query will be forced to load all the movies, then filter, and then sort — it won't be fast. You're probably better off sorting by score:

*[_type == "movies"] | score(name match "Harry*") | order(_score desc)

This will assign a high score to any movie with name match "Harry*", and a low score to everything else.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Alexander Staubo