vectordb-bench 0.0.16__py3-none-any.whl → 0.0.18__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -17,7 +17,7 @@ class config:
17
17
 
18
18
  DEFAULT_DATASET_URL = env.str("DEFAULT_DATASET_URL", AWS_S3_URL)
19
19
  DATASET_LOCAL_DIR = env.path("DATASET_LOCAL_DIR", "/tmp/vectordb_bench/dataset")
20
- NUM_PER_BATCH = env.int("NUM_PER_BATCH", 5000)
20
+ NUM_PER_BATCH = env.int("NUM_PER_BATCH", 100)
21
21
 
22
22
  DROP_OLD = env.bool("DROP_OLD", True)
23
23
  USE_SHUFFLED_DATA = env.bool("USE_SHUFFLED_DATA", True)
@@ -32,6 +32,7 @@ class DB(Enum):
32
32
  PgVectoRS = "PgVectoRS"
33
33
  PgVectorScale = "PgVectorScale"
34
34
  PgDiskANN = "PgDiskANN"
35
+ AlloyDB = "AlloyDB"
35
36
  Redis = "Redis"
36
37
  MemoryDB = "MemoryDB"
37
38
  Chroma = "Chroma"
@@ -97,6 +98,10 @@ class DB(Enum):
97
98
  if self == DB.AWSOpenSearch:
98
99
  from .aws_opensearch.aws_opensearch import AWSOpenSearch
99
100
  return AWSOpenSearch
101
+
102
+ if self == DB.AlloyDB:
103
+ from .alloydb.alloydb import AlloyDB
104
+ return AlloyDB
100
105
 
101
106
  @property
102
107
  def config_cls(self) -> Type[DBConfig]:
@@ -156,6 +161,10 @@ class DB(Enum):
156
161
  if self == DB.AWSOpenSearch:
157
162
  from .aws_opensearch.config import AWSOpenSearchConfig
158
163
  return AWSOpenSearchConfig
164
+
165
+ if self == DB.AlloyDB:
166
+ from .alloydb.config import AlloyDBConfig
167
+ return AlloyDBConfig
159
168
 
160
169
  def case_config_cls(self, index_type: IndexType | None = None) -> Type[DBCaseConfig]:
161
170
  if self == DB.Milvus:
@@ -197,6 +206,10 @@ class DB(Enum):
197
206
  if self == DB.PgDiskANN:
198
207
  from .pgdiskann.config import _pgdiskann_case_config
199
208
  return _pgdiskann_case_config.get(index_type)
209
+
210
+ if self == DB.AlloyDB:
211
+ from .alloydb.config import _alloydb_case_config
212
+ return _alloydb_case_config.get(index_type)
200
213
 
201
214
  # DB.Pinecone, DB.Chroma, DB.Redis
202
215
  return EmptyDBCaseConfig
@@ -0,0 +1,372 @@
1
+ """Wrapper around the alloydb vector database over VectorDB"""
2
+
3
+ import logging
4
+ import pprint
5
+ from contextlib import contextmanager
6
+ from typing import Any, Generator, Optional, Tuple, Sequence
7
+
8
+ import numpy as np
9
+ import psycopg
10
+ from pgvector.psycopg import register_vector
11
+ from psycopg import Connection, Cursor, sql
12
+
13
+ from ..api import VectorDB
14
+ from .config import AlloyDBConfigDict, AlloyDBIndexConfig, AlloyDBScaNNConfig
15
+
16
+ log = logging.getLogger(__name__)
17
+
18
+
19
+ class AlloyDB(VectorDB):
20
+ """Use psycopg instructions"""
21
+
22
+ conn: psycopg.Connection[Any] | None = None
23
+ cursor: psycopg.Cursor[Any] | None = None
24
+
25
+ _filtered_search: sql.Composed
26
+ _unfiltered_search: sql.Composed
27
+
28
+ def __init__(
29
+ self,
30
+ dim: int,
31
+ db_config: AlloyDBConfigDict,
32
+ db_case_config: AlloyDBIndexConfig,
33
+ collection_name: str = "alloydb_collection",
34
+ drop_old: bool = False,
35
+ **kwargs,
36
+ ):
37
+ self.name = "AlloyDB"
38
+ self.db_config = db_config
39
+ self.case_config = db_case_config
40
+ self.table_name = collection_name
41
+ self.dim = dim
42
+
43
+ self._index_name = "alloydb_index"
44
+ self._primary_field = "id"
45
+ self._vector_field = "embedding"
46
+
47
+ # construct basic units
48
+ self.conn, self.cursor = self._create_connection(**self.db_config)
49
+
50
+ # create vector extension
51
+ self.cursor.execute("CREATE EXTENSION IF NOT EXISTS alloydb_scann CASCADE")
52
+ self.conn.commit()
53
+
54
+ log.info(f"{self.name} config values: {self.db_config}\n{self.case_config}")
55
+ if not any(
56
+ (
57
+ self.case_config.create_index_before_load,
58
+ self.case_config.create_index_after_load,
59
+ )
60
+ ):
61
+ err = f"{self.name} config must create an index using create_index_before_load or create_index_after_load"
62
+ log.error(err)
63
+ raise RuntimeError(
64
+ f"{err}\n{pprint.pformat(self.db_config)}\n{pprint.pformat(self.case_config)}"
65
+ )
66
+
67
+ if drop_old:
68
+ self._drop_index()
69
+ self._drop_table()
70
+ self._create_table(dim)
71
+ if self.case_config.create_index_before_load:
72
+ self._create_index()
73
+
74
+ self.cursor.close()
75
+ self.conn.close()
76
+ self.cursor = None
77
+ self.conn = None
78
+
79
+ @staticmethod
80
+ def _create_connection(**kwargs) -> Tuple[Connection, Cursor]:
81
+ conn = psycopg.connect(**kwargs)
82
+ register_vector(conn)
83
+ conn.autocommit = False
84
+ cursor = conn.cursor()
85
+
86
+ assert conn is not None, "Connection is not initialized"
87
+ assert cursor is not None, "Cursor is not initialized"
88
+ return conn, cursor
89
+
90
+ def _generate_search_query(self, filtered: bool=False) -> sql.Composed:
91
+ search_query = sql.Composed(
92
+ [
93
+ sql.SQL(
94
+ "SELECT id FROM public.{table_name} {where_clause} ORDER BY embedding "
95
+ ).format(
96
+ table_name=sql.Identifier(self.table_name),
97
+ where_clause=sql.SQL("WHERE id >= %s") if filtered else sql.SQL(""),
98
+ ),
99
+ sql.SQL(self.case_config.search_param()["metric_fun_op"]),
100
+ sql.SQL(" %s::vector LIMIT %s::int"),
101
+ ]
102
+ )
103
+ return search_query
104
+
105
+ @contextmanager
106
+ def init(self) -> Generator[None, None, None]:
107
+ """
108
+ Examples:
109
+ >>> with self.init():
110
+ >>> self.insert_embeddings()
111
+ >>> self.search_embedding()
112
+ """
113
+
114
+ self.conn, self.cursor = self._create_connection(**self.db_config)
115
+
116
+ # index configuration may have commands defined that we should set during each client session
117
+ session_options: Sequence[dict[str, Any]] = self.case_config.session_param()["session_options"]
118
+
119
+ if len(session_options) > 0:
120
+ for setting in session_options:
121
+ command = sql.SQL("SET {setting_name} " + "= {val};").format(
122
+ setting_name=sql.Identifier(setting['parameter']['setting_name']),
123
+ val=sql.Identifier(str(setting['parameter']['val'])),
124
+ )
125
+ log.debug(command.as_string(self.cursor))
126
+ self.cursor.execute(command)
127
+ self.conn.commit()
128
+
129
+ self._filtered_search = self._generate_search_query(filtered=True)
130
+ self._unfiltered_search = self._generate_search_query()
131
+
132
+ try:
133
+ yield
134
+ finally:
135
+ self.cursor.close()
136
+ self.conn.close()
137
+ self.cursor = None
138
+ self.conn = None
139
+
140
+ def _drop_table(self):
141
+ assert self.conn is not None, "Connection is not initialized"
142
+ assert self.cursor is not None, "Cursor is not initialized"
143
+ log.info(f"{self.name} client drop table : {self.table_name}")
144
+
145
+ self.cursor.execute(
146
+ sql.SQL("DROP TABLE IF EXISTS public.{table_name}").format(
147
+ table_name=sql.Identifier(self.table_name)
148
+ )
149
+ )
150
+ self.conn.commit()
151
+
152
+ def ready_to_load(self):
153
+ pass
154
+
155
+ def optimize(self):
156
+ self._post_insert()
157
+
158
+ def _post_insert(self):
159
+ log.info(f"{self.name} post insert before optimize")
160
+ if self.case_config.create_index_after_load:
161
+ self._drop_index()
162
+ self._create_index()
163
+
164
+ def _drop_index(self):
165
+ assert self.conn is not None, "Connection is not initialized"
166
+ assert self.cursor is not None, "Cursor is not initialized"
167
+ log.info(f"{self.name} client drop index : {self._index_name}")
168
+
169
+ drop_index_sql = sql.SQL("DROP INDEX IF EXISTS {index_name}").format(
170
+ index_name=sql.Identifier(self._index_name)
171
+ )
172
+ log.debug(drop_index_sql.as_string(self.cursor))
173
+ self.cursor.execute(drop_index_sql)
174
+ self.conn.commit()
175
+
176
+ def _set_parallel_index_build_param(self):
177
+ assert self.conn is not None, "Connection is not initialized"
178
+ assert self.cursor is not None, "Cursor is not initialized"
179
+
180
+ index_param = self.case_config.index_param()
181
+
182
+ if index_param["enable_pca"] is not None:
183
+ self.cursor.execute(
184
+ sql.SQL("SET scann.enable_pca TO {};").format(
185
+ index_param["enable_pca"]
186
+ )
187
+ )
188
+ self.cursor.execute(
189
+ sql.SQL("ALTER USER {} SET scann.enable_pca TO {};").format(
190
+ sql.Identifier(self.db_config["user"]),
191
+ index_param["enable_pca"],
192
+ )
193
+ )
194
+ self.conn.commit()
195
+
196
+ if index_param["maintenance_work_mem"] is not None:
197
+ self.cursor.execute(
198
+ sql.SQL("SET maintenance_work_mem TO {};").format(
199
+ index_param["maintenance_work_mem"]
200
+ )
201
+ )
202
+ self.cursor.execute(
203
+ sql.SQL("ALTER USER {} SET maintenance_work_mem TO {};").format(
204
+ sql.Identifier(self.db_config["user"]),
205
+ index_param["maintenance_work_mem"],
206
+ )
207
+ )
208
+ self.conn.commit()
209
+
210
+ if index_param["max_parallel_workers"] is not None:
211
+ self.cursor.execute(
212
+ sql.SQL("SET max_parallel_maintenance_workers TO '{}';").format(
213
+ index_param["max_parallel_workers"]
214
+ )
215
+ )
216
+ self.cursor.execute(
217
+ sql.SQL(
218
+ "ALTER USER {} SET max_parallel_maintenance_workers TO '{}';"
219
+ ).format(
220
+ sql.Identifier(self.db_config["user"]),
221
+ index_param["max_parallel_workers"],
222
+ )
223
+ )
224
+ self.cursor.execute(
225
+ sql.SQL("SET max_parallel_workers TO '{}';").format(
226
+ index_param["max_parallel_workers"]
227
+ )
228
+ )
229
+ self.cursor.execute(
230
+ sql.SQL(
231
+ "ALTER USER {} SET max_parallel_workers TO '{}';"
232
+ ).format(
233
+ sql.Identifier(self.db_config["user"]),
234
+ index_param["max_parallel_workers"],
235
+ )
236
+ )
237
+ self.cursor.execute(
238
+ sql.SQL(
239
+ "ALTER TABLE {} SET (parallel_workers = {});"
240
+ ).format(
241
+ sql.Identifier(self.table_name),
242
+ index_param["max_parallel_workers"],
243
+ )
244
+ )
245
+ self.conn.commit()
246
+
247
+ results = self.cursor.execute(
248
+ sql.SQL("SHOW max_parallel_maintenance_workers;")
249
+ ).fetchall()
250
+ results.extend(
251
+ self.cursor.execute(sql.SQL("SHOW max_parallel_workers;")).fetchall()
252
+ )
253
+ results.extend(
254
+ self.cursor.execute(sql.SQL("SHOW maintenance_work_mem;")).fetchall()
255
+ )
256
+ log.info(f"{self.name} parallel index creation parameters: {results}")
257
+
258
+ def _create_index(self):
259
+ assert self.conn is not None, "Connection is not initialized"
260
+ assert self.cursor is not None, "Cursor is not initialized"
261
+ log.info(f"{self.name} client create index : {self._index_name}")
262
+
263
+ index_param = self.case_config.index_param()
264
+ self._set_parallel_index_build_param()
265
+ options = []
266
+ for option in index_param["index_creation_with_options"]:
267
+ if option['val'] is not None:
268
+ options.append(
269
+ sql.SQL("{option_name} = {val}").format(
270
+ option_name=sql.Identifier(option['option_name']),
271
+ val=sql.Identifier(str(option['val'])),
272
+ )
273
+ )
274
+ if any(options):
275
+ with_clause = sql.SQL("WITH ({});").format(sql.SQL(", ").join(options))
276
+ else:
277
+ with_clause = sql.Composed(())
278
+
279
+ index_create_sql = sql.SQL(
280
+ """
281
+ CREATE INDEX IF NOT EXISTS {index_name} ON public.{table_name}
282
+ USING {index_type} (embedding {embedding_metric})
283
+ """
284
+ ).format(
285
+ index_name=sql.Identifier(self._index_name),
286
+ table_name=sql.Identifier(self.table_name),
287
+ index_type=sql.Identifier(index_param["index_type"]),
288
+ embedding_metric=sql.Identifier(index_param["metric"]),
289
+ )
290
+
291
+ index_create_sql_with_with_clause = (
292
+ index_create_sql + with_clause
293
+ ).join(" ")
294
+ log.debug(index_create_sql_with_with_clause.as_string(self.cursor))
295
+ self.cursor.execute(index_create_sql_with_with_clause)
296
+ self.conn.commit()
297
+
298
+ def _create_table(self, dim: int):
299
+ assert self.conn is not None, "Connection is not initialized"
300
+ assert self.cursor is not None, "Cursor is not initialized"
301
+
302
+ try:
303
+ log.info(f"{self.name} client create table : {self.table_name}")
304
+
305
+ # create table
306
+ self.cursor.execute(
307
+ sql.SQL(
308
+ "CREATE TABLE IF NOT EXISTS public.{table_name} (id BIGINT PRIMARY KEY, embedding vector({dim}));"
309
+ ).format(table_name=sql.Identifier(self.table_name), dim=dim)
310
+ )
311
+ self.conn.commit()
312
+ except Exception as e:
313
+ log.warning(
314
+ f"Failed to create alloydb table: {self.table_name} error: {e}"
315
+ )
316
+ raise e from None
317
+
318
+ def insert_embeddings(
319
+ self,
320
+ embeddings: list[list[float]],
321
+ metadata: list[int],
322
+ **kwargs: Any,
323
+ ) -> Tuple[int, Optional[Exception]]:
324
+ assert self.conn is not None, "Connection is not initialized"
325
+ assert self.cursor is not None, "Cursor is not initialized"
326
+
327
+ try:
328
+ metadata_arr = np.array(metadata)
329
+ embeddings_arr = np.array(embeddings)
330
+
331
+ with self.cursor.copy(
332
+ sql.SQL("COPY public.{table_name} FROM STDIN (FORMAT BINARY)").format(
333
+ table_name=sql.Identifier(self.table_name)
334
+ )
335
+ ) as copy:
336
+ copy.set_types(["bigint", "vector"])
337
+ for i, row in enumerate(metadata_arr):
338
+ copy.write_row((row, embeddings_arr[i]))
339
+ self.conn.commit()
340
+
341
+ if kwargs.get("last_batch"):
342
+ self._post_insert()
343
+
344
+ return len(metadata), None
345
+ except Exception as e:
346
+ log.warning(
347
+ f"Failed to insert data into alloydb table ({self.table_name}), error: {e}"
348
+ )
349
+ return 0, e
350
+
351
+ def search_embedding(
352
+ self,
353
+ query: list[float],
354
+ k: int = 100,
355
+ filters: dict | None = None,
356
+ timeout: int | None = None,
357
+ ) -> list[int]:
358
+ assert self.conn is not None, "Connection is not initialized"
359
+ assert self.cursor is not None, "Cursor is not initialized"
360
+
361
+ q = np.asarray(query)
362
+ if filters:
363
+ gt = filters.get("id")
364
+ result = self.cursor.execute(
365
+ self._filtered_search, (gt, q, k), prepare=True, binary=True
366
+ )
367
+ else:
368
+ result = self.cursor.execute(
369
+ self._unfiltered_search, (q, k), prepare=True, binary=True
370
+ )
371
+
372
+ return [int(i[0]) for i in result.fetchall()]
@@ -0,0 +1,147 @@
1
+ from typing import Annotated, Optional, TypedDict, Unpack
2
+
3
+ import click
4
+ import os
5
+ from pydantic import SecretStr
6
+
7
+ from vectordb_bench.backend.clients.api import MetricType
8
+
9
+ from ....cli.cli import (
10
+ CommonTypedDict,
11
+ cli,
12
+ click_parameter_decorators_from_typed_dict,
13
+ get_custom_case_config,
14
+ run,
15
+ )
16
+ from vectordb_bench.backend.clients import DB
17
+
18
+
19
+ class AlloyDBTypedDict(CommonTypedDict):
20
+ user_name: Annotated[
21
+ str, click.option("--user-name", type=str, help="Db username", required=True)
22
+ ]
23
+ password: Annotated[
24
+ str,
25
+ click.option("--password",
26
+ type=str,
27
+ help="Postgres database password",
28
+ default=lambda: os.environ.get("POSTGRES_PASSWORD", ""),
29
+ show_default="$POSTGRES_PASSWORD",
30
+ ),
31
+ ]
32
+
33
+ host: Annotated[
34
+ str, click.option("--host", type=str, help="Db host", required=True)
35
+ ]
36
+ db_name: Annotated[
37
+ str, click.option("--db-name", type=str, help="Db name", required=True)
38
+ ]
39
+ maintenance_work_mem: Annotated[
40
+ Optional[str],
41
+ click.option(
42
+ "--maintenance-work-mem",
43
+ type=str,
44
+ help="Sets the maximum memory to be used for maintenance operations (index creation). "
45
+ "Can be entered as string with unit like '64GB' or as an integer number of KB."
46
+ "This will set the parameters: max_parallel_maintenance_workers,"
47
+ " max_parallel_workers & table(parallel_workers)",
48
+ required=False,
49
+ ),
50
+ ]
51
+ max_parallel_workers: Annotated[
52
+ Optional[int],
53
+ click.option(
54
+ "--max-parallel-workers",
55
+ type=int,
56
+ help="Sets the maximum number of parallel processes per maintenance operation (index creation)",
57
+ required=False,
58
+ ),
59
+ ]
60
+
61
+
62
+
63
+ class AlloyDBScaNNTypedDict(AlloyDBTypedDict):
64
+ num_leaves: Annotated[
65
+ int,
66
+ click.option("--num-leaves", type=int, help="Number of leaves", required=True)
67
+ ]
68
+ num_leaves_to_search: Annotated[
69
+ int,
70
+ click.option("--num-leaves-to-search", type=int, help="Number of leaves to search", required=True)
71
+ ]
72
+ pre_reordering_num_neighbors: Annotated[
73
+ int,
74
+ click.option("--pre-reordering-num-neighbors", type=int, help="Pre-reordering number of neighbors", default=200)
75
+ ]
76
+ max_top_neighbors_buffer_size: Annotated[
77
+ int,
78
+ click.option("--max-top-neighbors-buffer-size", type=int, help="Maximum top neighbors buffer size", default=20_000)
79
+ ]
80
+ num_search_threads: Annotated[
81
+ int,
82
+ click.option("--num-search-threads", type=int, help="Number of search threads", default=2)
83
+ ]
84
+ max_num_prefetch_datasets: Annotated[
85
+ int,
86
+ click.option("--max-num-prefetch-datasets", type=int, help="Maximum number of prefetch datasets", default=100)
87
+ ]
88
+ quantizer: Annotated[
89
+ str,
90
+ click.option(
91
+ "--quantizer",
92
+ type=click.Choice(["SQ8", "FLAT"]),
93
+ help="Quantizer type",
94
+ default="SQ8"
95
+ )
96
+ ]
97
+ enable_pca: Annotated[
98
+ bool, click.option(
99
+ "--enable-pca",
100
+ type=click.Choice(["on", "off"]),
101
+ help="Enable PCA",
102
+ default="on"
103
+ )
104
+ ]
105
+ max_num_levels: Annotated[
106
+ int,
107
+ click.option(
108
+ "--max-num-levels",
109
+ type=click.Choice([1, 2]),
110
+ help="Maximum number of levels",
111
+ default=1
112
+ )
113
+ ]
114
+
115
+
116
+ @cli.command()
117
+ @click_parameter_decorators_from_typed_dict(AlloyDBScaNNTypedDict)
118
+ def AlloyDBScaNN(
119
+ **parameters: Unpack[AlloyDBScaNNTypedDict],
120
+ ):
121
+ from .config import AlloyDBConfig, AlloyDBScaNNConfig
122
+
123
+ parameters["custom_case"] = get_custom_case_config(parameters)
124
+ run(
125
+ db=DB.AlloyDB,
126
+ db_config=AlloyDBConfig(
127
+ db_label=parameters["db_label"],
128
+ user_name=SecretStr(parameters["user_name"]),
129
+ password=SecretStr(parameters["password"]),
130
+ host=parameters["host"],
131
+ db_name=parameters["db_name"],
132
+ ),
133
+ db_case_config=AlloyDBScaNNConfig(
134
+ num_leaves=parameters["num_leaves"],
135
+ quantizer=parameters["quantizer"],
136
+ enable_pca=parameters["enable_pca"],
137
+ max_num_levels=parameters["max_num_levels"],
138
+ num_leaves_to_search=parameters["num_leaves_to_search"],
139
+ max_top_neighbors_buffer_size=parameters["max_top_neighbors_buffer_size"],
140
+ pre_reordering_num_neighbors=parameters["pre_reordering_num_neighbors"],
141
+ num_search_threads=parameters["num_search_threads"],
142
+ max_num_prefetch_datasets=parameters["max_num_prefetch_datasets"],
143
+ max_parallel_workers=parameters["max_parallel_workers"],
144
+ maintenance_work_mem=parameters["maintenance_work_mem"],
145
+ ),
146
+ **parameters,
147
+ )