Improving query performance by optimizing Groq queries in Slack thread.

5 replies
Last updated: Sep 14, 2023
Is there a way to make this query more performant?
*[_id == $authorId][0] {
  "conferences": array::unique(*[_id in *[_type == "post" && references(^.^._id)].conferences[]->._id])[] {
    _id,
    "path": "/news/" + division->.slug.current + "/" + slug.current,
    name,
    shortName,
  } | order(name asc)
}
It's currently taking over 10 seconds to respond and timing out on Vercel
:face_holding_back_tears:
Sep 14, 2023, 4:16 AM
Yes, I believe there are a few things you could do. The dereference of
conferences[]->_id
adds a bunch of overhead and isn’t necessary, since you’re only getting the
_id
and that’s equal to the
_ref
of the reference. I also changed your grandparent
_id
check to the
$authorId
param, since you already know that value. Please try something like this and see if it’s better:

*[_id == $authorId][0] {
  "conferences": array::unique(*[_id in *[_type == "post" && references($authorId)].conferences[]._ref])[] {
    _id,
    "path": "/news/" + division->.slug.current + "/" + slug.current,
    name,
    shortName,
  } | order(name asc)
}
Sep 14, 2023, 6:05 AM
Oh wow! That went from 10-14 seconds down to anywhere from 100 ms to 2 seconds
Sep 14, 2023, 2:34 PM
Great! Thanks for confirming. There’s a canonical guide from Alex on writing performant queries that you may have already seen, but others coming across this thread may not have.
Sep 14, 2023, 2:39 PM
Switch
references(^.^._id)
to
references($authorId)
was new for me and I keep forgetting that
conferences[]->._id
is the same as the ref 🤦‍♂️
Sep 14, 2023, 2:40 PM
I’d be interested to see benchmarks on the change from using the parent operator to using the query param. I’m not sure it will improve anything, but it might, and won’t hurt anything. You could append
explain=true
as a query parameter (i.e., append it to the URL) to compare the process that each takes. The output is difficult to parse, but you may be able to infer some tendencies/generalities.
Sep 14, 2023, 2:43 PM

Sanity– build remarkable experiences at scale

The Sanity Composable Content Cloud is the 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?