Skip to content

Instantly share code, notes, and snippets.

@JavascriptMick
Last active January 22, 2024 08:52
Show Gist options
  • Save JavascriptMick/8bf8d4eca3d29d08203ac97a52a6f8ab to your computer and use it in GitHub Desktop.
Save JavascriptMick/8bf8d4eca3d29d08203ac97a52a6f8ab to your computer and use it in GitHub Desktop.
Invoke PostgreSQL function with vector parameter using Prisma $queryRaw
--I'm assuming you have already added the 'pgvector' extension to PostgreSQL (https://github.com/pgvector/pgvector)
--looks wierd but you invoke the function using select, representing the vector as a string literal..
select * from public.test_function('[1.03, 2.45, 3.56]', .06);
import { Prisma} from '@prisma/client';
import prisma_client from 'prisma.client';
//for stateless 'DAO' style services like this, I have started using Namespaces..
export namespace MyService {
//use $queryRaw to build up the sql, replicate the wierd string literal array. Prisma.raw is used to tell prisma not to mess with the literal
export async function callTestFunction(
query_embedding: number[],
similarity_threshold: number = 0.05
) {
return prisma_client.$queryRaw`
SELECT * FROM public.test_function(
${Prisma.raw(`'[${query_embedding.join(',')}]'`)},
${similarity_threshold}::double precision
)`;
}
}
import { PrismaClient } from '@prisma/client';
const prisma_client = new PrismaClient();
export default prisma_client;
CREATE OR REPLACE FUNCTION public.test_function(
query_embedding vector,
similarity_threshold double precision DEFAULT 0.05
)
RETURNS TABLE(test text)
LANGUAGE sql
STABLE
AS $function$
--you would normally use query_embedding to do a distance query using <=> etc... but for test just return rubbish
select 'passed' as test;
$function$
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment