Querying and expanding references in Sanity.io search queries

11 replies
Last updated: May 14, 2021
I’m in the process of building a search query and would like to guidance on search and expanding references.My query thus far:

*[title match $q || address match $q]{
  ...,
  "artist": artist -> name,
  "mainImage": image.asset->
  }
This works fine for finding documents where the query matches title or address but the results do not expand the artist or mainImage references. What am I doing wrong?
Also, how should I structure this query so I can also search the artist.name (expanded reference) field with the $q param?
Thank you!
May 13, 2021, 2:24 PM
That’s exactly what I get if I change the code to your snippet
May 13, 2021, 8:47 PM
That’s really odd then that when you add
->
after each, you’re not getting the dereferenced documents.
May 13, 2021, 8:48 PM
Is artist an array of references? That might explain why
"artist": artist
returns refs but
"artist": artist->
does not.
May 13, 2021, 8:52 PM
If that’s the case, you’d want
'artist': artist[]->name
.
May 13, 2021, 8:52 PM
I apologize I mis spoke in my original post.The refernces are getting expanded, the wall I’m hitting it how I can apply the
match
$q to the reference fields
May 13, 2021, 8:52 PM
For example, I have an artist.name “Isamu Noguchi”, but this query:
*[title match $q || address match $q || artist match $q]{

...,

"artist": artist[] -> name,

"mainImage": image.asset->

}
returns nothing on the
$q
“Isamu”.Whereas there is (an unreferenced)
artwork
called “Sunken Garden” and the $q “Sunken” works fine
May 13, 2021, 8:55 PM
I suppose I could query all the documents and filter in the frontend but that seems wasteful
May 13, 2021, 8:58 PM
If I understand what you’re after, I think there are a few ways this could be approached. If we look at just your filter, are you hoping to get one type of document back? If it’s a type of
artwork
, you might need to change your filter to match from that perspective (e.g.,
... || artist[]->name match $q
).
May 13, 2021, 9:10 PM
You could also do a join —something like:

*[...] {
  'artist': *[_type == 'artist' && name == $q && _id in ^.artist[]._ref]
}[count(artist) > 0]
May 13, 2021, 9:12 PM
Thanks
user A
that did it. Looking over the GROQ cheat sheet again I can see how this answer could be extrapolated from the docs but this seems to me a worthwhile addition to the examples.Thanks again!
May 13, 2021, 9:29 PM
Glad to hear it's working for you!
May 14, 2021, 2:02 AM

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?

Categorized in