|
| 1 | +import pgvector.psycopg |
| 2 | +import psycopg |
| 3 | + |
| 4 | +from benchmark.dataset import Dataset |
| 5 | +from engine.base_client import IncompatibilityError |
| 6 | +from engine.base_client.configure import BaseConfigurator |
| 7 | +from engine.base_client.distances import Distance |
| 8 | +from engine.clients.pgvector.config import get_db_config |
| 9 | + |
| 10 | + |
| 11 | +class PgVectorConfigurator(BaseConfigurator): |
| 12 | + DISTANCE_MAPPING = { |
| 13 | + Distance.L2: "vector_l2_ops", |
| 14 | + Distance.COSINE: "vector_cosine_ops", |
| 15 | + } |
| 16 | + |
| 17 | + def __init__(self, host, collection_params: dict, connection_params: dict): |
| 18 | + super().__init__(host, collection_params, connection_params) |
| 19 | + self.conn = psycopg.connect(**get_db_config(host, connection_params)) |
| 20 | + print("configure connection created") |
| 21 | + self.conn.execute("CREATE EXTENSION IF NOT EXISTS vector;") |
| 22 | + pgvector.psycopg.register_vector(self.conn) |
| 23 | + |
| 24 | + def clean(self): |
| 25 | + self.conn.execute( |
| 26 | + "DROP TABLE IF EXISTS items CASCADE;", |
| 27 | + ) |
| 28 | + |
| 29 | + def recreate(self, dataset: Dataset, collection_params): |
| 30 | + if dataset.config.distance == Distance.DOT: |
| 31 | + raise IncompatibilityError |
| 32 | + |
| 33 | + self.conn.execute( |
| 34 | + f"""CREATE TABLE items ( |
| 35 | + id SERIAL PRIMARY KEY, |
| 36 | + embedding vector({dataset.config.vector_size}) NOT NULL |
| 37 | + );""" |
| 38 | + ) |
| 39 | + self.conn.execute("ALTER TABLE items ALTER COLUMN embedding SET STORAGE PLAIN") |
| 40 | + |
| 41 | + try: |
| 42 | + hnsw_distance_type = self.DISTANCE_MAPPING[dataset.config.distance] |
| 43 | + except KeyError: |
| 44 | + raise IncompatibilityError( |
| 45 | + f"Unsupported distance metric: {dataset.config.distance}" |
| 46 | + ) |
| 47 | + |
| 48 | + self.conn.execute( |
| 49 | + f"CREATE INDEX on items USING hnsw(embedding {hnsw_distance_type}) WITH (m = {collection_params['hnsw_config']['m']}, ef_construction = {collection_params['hnsw_config']['ef_construct']})" |
| 50 | + ) |
| 51 | + |
| 52 | + self.conn.close() |
| 53 | + |
| 54 | + def delete_client(self): |
| 55 | + self.conn.close() |
0 commit comments