Skip to content

Instantly share code, notes, and snippets.

@a-churchill
Last active April 20, 2024 09:49
Show Gist options
  • Save a-churchill/71a06bacfd5c5bc2a6fad6650b6d9898 to your computer and use it in GitHub Desktop.
Save a-churchill/71a06bacfd5c5bc2a6fad6650b6d9898 to your computer and use it in GitHub Desktop.
Documentation Search in Sanity

Documentation Search in Sanity

This Gist contains a sample query for searching text content in GROQ, Sanity's custom query language. We use something similar to this for Causal's documentation site. See more on our blog!

*[_type == "docPage"]
| score(
boost(title match $queryString, 7),
boost(description match $queryString, 1),
boost(pt::text(content) match $queryString, 0.5)
)
{
_score,
title,
content,
...
}[ _score > 0 ]
| order(_score desc)[0...$limit]
// This is the code we use to convert a user's raw text query to the `queryString` we pass
// to the GROQ query above
// For example, "category agg" would be converted to "*category* *agg*"
const queryString = query
.trim()
.replaceAll(/\s+/g, " ") // replace multiple spaces with a single space
.split(" ")
.map(s => `*${s}*`) // allow partial matches (e.g. "agg" can match "aggregation")
.join(" ");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment