From: svim-ig (@svim-ig) <noreply+svim-ig@github.com>
To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>
Subject: [pgvector/pgvector] issue #737: Bulk Upsert into PGVector Database
Date: Mon, 23 Dec 2024 05:02:15 +0000
Message-ID: <gh-pgvector-pgvector-737@github.com> (raw)
I am unable to Upsert data having more than 4000 embeddings into PGVector Database in Azure from Azure databricks using psycopg2....is there any best practices for bulk upsert into PGVector database or Postgress from databricks using parallelization of nodes in databricks without breaking data? I am having 1M records
import psycopg2
from psycopg2.extras import execute_values
### Typical Code is as below:
def upsert_partition(partition, table_name):
conn = psycopg2.connect(
host="myhost.postgres.database.azure.com",
database="postgres",
port=5432,
user="admin",
password="password"
)
cur = conn.cursor()
values = [
(row['col1'],
row['col2'],
row['col3'],
row['col4'], # product description
row['col5']) # Product embeddings
for row in partition
]
# Loop through the values and execute the upsert one at a time
insert_query = f"""
INSERT INTO {table_name}
(col1, col2, col3, col4, col5)
VALUES %s
ON CONFLICT (col1, col2, col3) ...key column combination
DO UPDATE
SET
col4 = EXCLUDED.col4,
col5 = EXCLUDED.col5;
"""
try:
# Insert all values at once using execute_values for efficiency (no batching)
execute_values(cur, insert_query, values)
conn.commit()
except Exception as e:
conn.rollback()
print(f"Error executing upsert: {e}")
raise e
finally:
cur.close()
conn.close()
upsert_df = upsert_df.repartition(80) (dataset with 1M records)
df1_upsert.rdd.foreachPartition(lambda partition: upsert_partition(partition, table_name))