🔮 Sanity Create is here. Writing is reinvented. Try now, no developer setup

Improving a GROQ query for searching posts and services

8 replies
Last updated: May 3, 2023
How can I improve this query? I know I am missing stuff (just not sure what it is), but I basically want to search and if the text matches a post's title or text in the body return it along with any services where the query matches the service title or description. However, I want to also add if a post or service is tagged or in a category that loosely matches the query... i.e. if someone searches "Food Bank", posts and services in the "Food Banks" category should still show up.
export const search = groq`*[
  (_type == "post" && (title match "*" + $query + "*" || pt::text(body) match "*" + $query + "*")) ||
  (_type == "service" && (title match "*" + $query + "*" || description match "*" + $query + "*"))
]{
  ...
}`
May 2, 2023, 6:26 AM
user T
sorry for the ping but I have a demo of this website coming up today/tomorrow and was curious if you had any insight or know anyone that does on something like this :gratitude-thank-you:
May 2, 2023, 4:25 PM
Hey User, not quite sure sorry. Building a search with GROQ is among the things I have to raise my hand and say I’ve never done!
Think I’d start by intercepting the network requests when using search in the Studio for some pointers. Wish I had a better answer than that!
May 2, 2023, 4:28 PM
How can I go about intercepting that?
May 2, 2023, 6:15 PM
Network tab in chrome inspect
May 2, 2023, 7:05 PM
And that shows the groq query? Cool
May 2, 2023, 7:08 PM
Kinda, it's pretty hard to interpret, I'm sure it's possible
May 2, 2023, 7:10 PM
So I think I figured it out
export const search = groq`*[
  (_type == "post" && (title match "*" + $query + "*" || pt::text(body) match "*" + $query + "*" || tags[]->title match "*" + $query + "*" || categories[]->title match "*" + $query + "*")) ||
  (_type == "service" && (title match "*" + $query + "*" || description match "*" + $query + "*" || tags[]->title match "*" + $query + "*" || categories[]->title match "*" + $query + "*"))
]{
  ...,
  _type == "post" => {
    ${postFields}
  },
}`
Kind of messy but
🤷
May 3, 2023, 12:20 AM
On a lark I looked at some of the queries for my studio when using the actual built-in search feature, and at least to my layperson eye it doesn't seem enormously different, so take comfort in that! 🙂
May 3, 2023, 3:31 PM

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?