Database / pgvector basics Interview Questions
How do you insert and update vector data in pgvector?
Vector values are inserted as SQL string literals in the format '[v1,v2,...,vn]' - a JSON array-like notation enclosed in single quotes. PostgreSQL automatically casts these to the vector type.
-- Insert a single row with a vector literal INSERT INTO documents (content, embedding) VALUES ('Hello world', '[0.1, 0.2, 0.3, ...]'); -- Insert multiple rows in one statement INSERT INTO documents (id, content, embedding) VALUES (1, 'Python tutorial', '[0.11, 0.22, 0.33]'), (2, 'JavaScript guide', '[0.44, 0.55, 0.66]'), (3, 'Hiking tips', '[0.77, 0.88, 0.99]'); -- Insert from a Python list (psycopg2) # import psycopg2 # embedding = [0.1, 0.2, 0.3] # list of floats from embedding model # cur.execute( # "INSERT INTO documents (content, embedding) VALUES (%s, %s)", # (text, embedding) # psycopg2 converts list to vector literal # ) -- Update an existing embedding: UPDATE documents SET embedding = '[0.11, 0.21, 0.31]' WHERE id = 1; -- Upsert (insert or update on conflict): INSERT INTO documents (id, content, embedding) VALUES (1, 'Updated Python tutorial', '[0.12, 0.23, 0.34]') ON CONFLICT (id) DO UPDATE SET content = EXCLUDED.content, embedding = EXCLUDED.embedding; -- Cast a text literal to vector explicitly: SELECT '[1,2,3]'::vector; -- explicit cast notation SELECT CAST('[1,2,3]' AS vector(3));
More Related questions...