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));
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
