-- Connect to your database and run:
CREATE EXTENSION IF NOT EXISTS vector;
-- Example table with an embedding column of dimension 1536 (adjust dimension as necessary)
CREATE TABLE IF NOT EXISTS items (
id SERIAL PRIMARY KEY,
description TEXT,
embedding vector(1536)
);
import psycopg2
from psycopg2.extras import execute_values
# Connection params - replace with your own
DB_PARAMS = {
'host': 'localhost',
'port': 5432,
'dbname': 'your_db',
'user': 'your_user',
'password': 'your_password'
}
def insert_embedding(description, embedding_vector):
"""
Insert a record with embedding vector into the DB.
embedding_vector: list or tuple of floats
"""
# Convert embedding vector to Postgres array literal string, e.g. '[0.1, 0.2, ...]'
# Actually psycopg2 can handle it automatically as list -> pg vector, so no need to stringify
insert_query = """
INSERT INTO items (description, embedding) VALUES (%s, %s)
"""
try:
with psycopg2.connect(**DB_PARAMS) as conn:
with conn.cursor() as cur:
cur.execute(insert_query, (description, embedding_vector))
conn.commit()
print("Embedding inserted successfully.")
except Exception as e:
print(f"Error inserting embedding: {e}")
# Example usage:
if __name__ == "__main__":
# Example 1536-d embedding vector (use the actual embedding from your model)
example_embedding = [0.01] * 1536
insert_embedding("Example item", example_embedding)
If you want code to create the table, insert multiple embeddings, or do similarity searches, just ask!