Ordering search results by search term hierarchy in GROQ
Yes, you can definitely order search results by match priority using the score() and boost() functions in GROQ!
Here's how to prioritize title matches over subtitle matches:
*[title match "whatever" || subtitle match "whatever"]
| score(
boost(title match "whatever", 4),
boost(subtitle match "whatever", 1)
)
| order(_score desc)How it works:
- The score() function computes a relevance score for each document based on your criteria
- The
boost()function assigns different weights to each condition - in this case, title matches get a weight of 4, while subtitle matches get a weight of 1 - Results are ordered by the computed
_scorefield in descending order, so title matches appear first
The _score field is automatically added to each document when you use the score() function, and you can adjust the boost weights to whatever ratio makes sense for your use case. Higher numbers = higher priority in the results.
You can also use this pattern with variables to make it more reusable:
*[title match $term || subtitle match $term]
| score(
boost(title match $term, 4),
boost(subtitle match $term, 1)
)
| order(_score desc)This approach is super flexible - you can add as many scoring criteria as you need with different weights to fine-tune your search result ranking!
Sanity – Build the way you think, not the way your CMS thinks
Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.