Semantic Search
Semantic Search with pgvector and Supabase Edge Functions
Semantic search interprets the meaning behind user queries rather than exact keywords. It uses machine learning to capture the intent and context behind the query, handling language nuances like synonyms, phrasing variations, and word relationships.
Since Supabase Edge Runtime v1.36.0 you can run the gte-small
model natively within Supabase Edge Functions without any external dependencies! This allows you to easily generate text embeddings without calling any external APIs!
In this tutorial you're implementing three parts:
- A
generate-embedding
database webhook edge function which generates embeddings when a content row is added (or updated) in thepublic.embeddings
table. - A
query_embeddings
Postgres function which allows us to perform similarity search from an egde function via Remote Procedure Call (RPC). - A
search
edge function which generates the embedding for the search term, performs the similarity search via RPC function call, and returns the result.
You can find the complete example code on GitHub
Create the database table and webhook
Given the following table definition:
You can deploy the following edge function as a database webhook to generate the embeddings for any text content inserted into the table:
Create a Database Function and RPC
With the embeddings now stored in your Postgres database table, you can query them from Supabase Edge Functions by utilizing Remote Procedure Calls (RPC).
Given the following Postgres Function:
Query vectors in Supabase Edge Functions
You can use supabase-js
to first generate the embedding for the search term and then invoke the Postgres function to find the relevant results from your stored embeddings, right from your Supabase Edge Function:
That's it, you now have AI powered semantic search set up without any external dependencies! Just you, pgvector, and Supabase Edge Functions!