Fri Jun 30 2023
A simple text search using Sanity and groq
This post describes a way to use groq to search Sanity for content. This includes searching simple strings and portable text fields, then sorting the results by using the score and boost functions in groq.
PS: This is a simple search using only groq, a query language. It doesn't handle spelling errors, synonyms and other stuff you might find in a dedicated search engine.
The document
Lets say that we have the following schema for an article.
The goal
Let's say we want to search the title, description and the body. We want hits to be ranked in such a way that a hit in the title should be ranked above the description, and the description above the body text.
Defining the search
This is how the full query could look.
Let's take this step by step to make it more understandable.
Using the result, you can filter out documents with a score of 0 and the sort the resulting array of documents using the _score
field. You can also do the filtering and sorting in the query itself.
As stated at the top, this doesn't replace a dedicated search engine, but it might work for smaller project or situations where you are selecting documents rather than doing a full text search.