How to implement user search query in custom Sanity movie app?
Absolutely! You can implement user search functionality in your custom movie app using Sanity. Here's how to approach it:
Basic Approach
You'll want to use the Sanity Client to query your content based on user input. First, install it:
npm install @sanity/clientThen set up a client instance in your app:
import {createClient} from '@sanity/client'
const client = createClient({
projectId: 'your-project-id',
dataset: 'production',
apiVersion: '2024-01-01',
useCdn: true, // for faster cached responses
})Implementing Search with GROQ
For text-based searches, you'll use GROQ's match operator, which performs full-text search with tokenization. Here's an example for searching movies:
async function searchMovies(searchTerm) {
const query = `*[_type == "movie" && (
title match $searchTerm ||
overview match $searchTerm ||
cast[].name match $searchTerm
)]`
return await client.fetch(query, { searchTerm })
}Adding Relevance Scoring
To rank your search results by relevance, use the score() function to weight different fields:
const query = `*[_type == "movie" && (
title match $searchTerm ||
overview match $searchTerm
)] | score(
boost(title match $searchTerm, 3),
boost(overview match $searchTerm, 1)
) | order(_score desc)`
const results = await client.fetch(query, { searchTerm: userInput })This gives title matches 3x more weight than overview matches, ensuring more relevant results appear first.
Important Notes
- The
matchoperator tokenizes text, so it's great for free-text search but not exact string matching - Use wildcards with caution:
match "demo*"works, but special characters like@and.are treated as word separators - For better performance on public content, use
useCdn: truein your client config - Consider debouncing your search input to avoid excessive API calls
The combination of the Sanity Client, GROQ's match operator, and the score() function gives you a powerful, flexible search implementation that's perfect for a movie app!
Show original thread26 replies
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.