Unlock seamless workflows and faster delivery with our latest releases- get the details

JavaScript Query Params - How to Sort Results Using Params

6 replies
Last updated: Dec 15, 2021
Another question: is there a way to sort results based on query params? Currently I’m doing this:
| order(date ${query.sort})
…where
${query.sort}
is a JavaScript expression inside a template string, but I’m curious if this can be done using params.
Dec 15, 2021, 10:06 AM
Yes. You can do this:
* | order(select(
  $sort == "title" => title,
  $sort == "date" => date,
  _id))
This is like a
switch
statement in JS.
Dec 15, 2021, 10:10 AM
Thank you!
Dec 15, 2021, 10:11 AM
The downside is that this code path is not optimized at the moment. All the documents will be loaded into memory and sorted first, which can be inefficient if you have a lot of documents. How inefficient depends on the size of the documents and so on, so I can’t give you an exact number. But I would recommend not doing it unless you know that the number of documents (after filtering) is less than 1,000 or 1MB.
Dec 15, 2021, 10:12 AM
So I should stick with the template literal method for performance, in other words?
Dec 15, 2021, 10:13 AM
If possible. Note that the above trick also breaks our ability to optimize slicing. So if you have this:
*[some filter that returns 1 million documents]
  | order(select(...)) [0..100]
…then the slow/inefficient ordering will happen on those 1 million documents, even though you’re only extracting 100. With a normal
order()
, we can slice while sorting, which is much faster.
Dec 15, 2021, 10:17 AM
Thanks for the information!
Dec 15, 2021, 10:17 AM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?