|
| 1 | +import logging |
| 2 | +from contextlib import contextmanager |
| 3 | + |
| 4 | +import mysql.connector as mysql |
| 5 | +import numpy as np |
| 6 | + |
| 7 | +from ..api import VectorDB |
| 8 | +from .config import AliSQLConfigDict, AliSQLIndexConfig |
| 9 | + |
| 10 | +log = logging.getLogger(__name__) |
| 11 | + |
| 12 | + |
| 13 | +class AliSQL(VectorDB): |
| 14 | + def __init__( |
| 15 | + self, |
| 16 | + dim: int, |
| 17 | + db_config: AliSQLConfigDict, |
| 18 | + db_case_config: AliSQLIndexConfig, |
| 19 | + collection_name: str = "vec_collection", |
| 20 | + drop_old: bool = False, |
| 21 | + **kwargs, |
| 22 | + ): |
| 23 | + self.name = "AliSQL" |
| 24 | + self.db_config = db_config |
| 25 | + self.case_config = db_case_config |
| 26 | + self.db_name = "vectordbbench" |
| 27 | + self.table_name = collection_name |
| 28 | + self.dim = dim |
| 29 | + |
| 30 | + # construct basic units |
| 31 | + self.conn, self.cursor = self._create_connection() |
| 32 | + |
| 33 | + if drop_old: |
| 34 | + self._drop_db() |
| 35 | + self._create_db_table(dim) |
| 36 | + |
| 37 | + self.cursor.close() |
| 38 | + self.conn.close() |
| 39 | + self.cursor = None |
| 40 | + self.conn = None |
| 41 | + |
| 42 | + def _create_connection(self): |
| 43 | + conn = mysql.connect( |
| 44 | + host=self.db_config["host"], |
| 45 | + user=self.db_config["user"], |
| 46 | + port=self.db_config["port"], |
| 47 | + password=self.db_config["password"], |
| 48 | + buffered=True, |
| 49 | + ) |
| 50 | + cursor = conn.cursor() |
| 51 | + |
| 52 | + assert conn is not None, "Connection is not initialized" |
| 53 | + assert cursor is not None, "Cursor is not initialized" |
| 54 | + |
| 55 | + return conn, cursor |
| 56 | + |
| 57 | + def _drop_db(self): |
| 58 | + assert self.conn is not None, "Connection is not initialized" |
| 59 | + assert self.cursor is not None, "Cursor is not initialized" |
| 60 | + log.info(f"{self.name} client drop db : {self.db_name}") |
| 61 | + |
| 62 | + # flush tables before dropping database to avoid some locking issue |
| 63 | + self.cursor.execute("FLUSH TABLES") |
| 64 | + self.cursor.execute(f"DROP DATABASE IF EXISTS {self.db_name}") |
| 65 | + self.cursor.execute("COMMIT") |
| 66 | + self.cursor.execute("FLUSH TABLES") |
| 67 | + |
| 68 | + def _create_db_table(self, dim: int): |
| 69 | + assert self.conn is not None, "Connection is not initialized" |
| 70 | + assert self.cursor is not None, "Cursor is not initialized" |
| 71 | + |
| 72 | + try: |
| 73 | + log.info(f"{self.name} client create database : {self.db_name}") |
| 74 | + self.cursor.execute(f"CREATE DATABASE {self.db_name}") |
| 75 | + |
| 76 | + log.info(f"{self.name} client create table : {self.table_name}") |
| 77 | + self.cursor.execute(f"USE {self.db_name}") |
| 78 | + |
| 79 | + self.cursor.execute( |
| 80 | + f""" |
| 81 | + CREATE TABLE {self.table_name} ( |
| 82 | + id INT PRIMARY KEY, |
| 83 | + v VECTOR({self.dim}) NOT NULL |
| 84 | + ) |
| 85 | + """ |
| 86 | + ) |
| 87 | + self.cursor.execute("COMMIT") |
| 88 | + |
| 89 | + except Exception as e: |
| 90 | + log.warning(f"Failed to create table: {self.table_name} error: {e}") |
| 91 | + raise e from None |
| 92 | + |
| 93 | + @contextmanager |
| 94 | + def init(self): |
| 95 | + """create and destory connections to database. |
| 96 | +
|
| 97 | + Examples: |
| 98 | + >>> with self.init(): |
| 99 | + >>> self.insert_embeddings() |
| 100 | + """ |
| 101 | + self.conn, self.cursor = self._create_connection() |
| 102 | + |
| 103 | + index_param = self.case_config.index_param() |
| 104 | + search_param = self.case_config.search_param() |
| 105 | + |
| 106 | + # maximize allowed package size |
| 107 | + self.cursor.execute("SET GLOBAL max_allowed_packet = 1073741824") |
| 108 | + |
| 109 | + if index_param["index_type"] == "HNSW": |
| 110 | + if index_param["cache_size"] is not None: |
| 111 | + self.cursor.execute(f"SET GLOBAL vidx_hnsw_cache_size = {index_param['cache_size']}") |
| 112 | + if search_param["ef_search"] is not None: |
| 113 | + self.cursor.execute(f"SET GLOBAL vidx_hnsw_ef_search = {search_param['ef_search']}") |
| 114 | + self.cursor.execute("COMMIT") |
| 115 | + |
| 116 | + self.insert_sql = f"INSERT INTO {self.db_name}.{self.table_name} (id, v) VALUES (%s, %s)" # noqa: S608 |
| 117 | + self.select_sql = ( |
| 118 | + f"SELECT id FROM {self.db_name}.{self.table_name} " # noqa: S608 |
| 119 | + f"ORDER by vec_distance_{search_param['metric_type']}(v, %s) LIMIT %s" |
| 120 | + ) |
| 121 | + self.select_sql_with_filter = ( |
| 122 | + f"SELECT id FROM {self.db_name}.{self.table_name} WHERE id >= %s " # noqa: S608 |
| 123 | + f"ORDER by vec_distance_{search_param['metric_type']}(v, %s) LIMIT %s" |
| 124 | + ) |
| 125 | + |
| 126 | + try: |
| 127 | + yield |
| 128 | + finally: |
| 129 | + self.cursor.close() |
| 130 | + self.conn.close() |
| 131 | + self.cursor = None |
| 132 | + self.conn = None |
| 133 | + |
| 134 | + def ready_to_load(self) -> bool: |
| 135 | + pass |
| 136 | + |
| 137 | + def optimize(self, data_size: int) -> None: |
| 138 | + assert self.conn is not None, "Connection is not initialized" |
| 139 | + assert self.cursor is not None, "Cursor is not initialized" |
| 140 | + |
| 141 | + index_param = self.case_config.index_param() |
| 142 | + |
| 143 | + try: |
| 144 | + index_options = f"DISTANCE={index_param['metric_type']}" |
| 145 | + if index_param["index_type"] == "HNSW" and index_param["M"] is not None: |
| 146 | + index_options += f" M={index_param['M']}" |
| 147 | + |
| 148 | + self.cursor.execute( |
| 149 | + f""" |
| 150 | + ALTER TABLE {self.db_name}.{self.table_name} |
| 151 | + ADD VECTOR KEY v(v) {index_options} |
| 152 | + """ |
| 153 | + ) |
| 154 | + self.cursor.execute("COMMIT") |
| 155 | + |
| 156 | + except Exception as e: |
| 157 | + log.warning(f"Failed to create index: {self.table_name} error: {e}") |
| 158 | + raise e from None |
| 159 | + |
| 160 | + @staticmethod |
| 161 | + def vector_to_hex(v): # noqa: ANN001 |
| 162 | + return np.array(v, "float32").tobytes() |
| 163 | + |
| 164 | + def insert_embeddings( |
| 165 | + self, |
| 166 | + embeddings: list[list[float]], |
| 167 | + metadata: list[int], |
| 168 | + **kwargs, |
| 169 | + ) -> tuple[int, Exception]: |
| 170 | + """Insert embeddings into the database. |
| 171 | + Should call self.init() first. |
| 172 | + """ |
| 173 | + assert self.conn is not None, "Connection is not initialized" |
| 174 | + assert self.cursor is not None, "Cursor is not initialized" |
| 175 | + |
| 176 | + try: |
| 177 | + metadata_arr = np.array(metadata) |
| 178 | + embeddings_arr = np.array(embeddings) |
| 179 | + |
| 180 | + batch_data = [] |
| 181 | + for i, row in enumerate(metadata_arr): |
| 182 | + batch_data.append((int(row), self.vector_to_hex(embeddings_arr[i]))) |
| 183 | + |
| 184 | + self.cursor.executemany(self.insert_sql, batch_data) |
| 185 | + self.cursor.execute("COMMIT") |
| 186 | + self.cursor.execute("FLUSH TABLES") |
| 187 | + |
| 188 | + return len(metadata), None |
| 189 | + except Exception as e: |
| 190 | + log.warning(f"Failed to insert data into Vector table ({self.table_name}), error: {e}") |
| 191 | + return 0, e |
| 192 | + |
| 193 | + def search_embedding( |
| 194 | + self, |
| 195 | + query: list[float], |
| 196 | + k: int = 100, |
| 197 | + filters: dict | None = None, |
| 198 | + timeout: int | None = None, |
| 199 | + **kwargs, |
| 200 | + ) -> list[int]: |
| 201 | + assert self.conn is not None, "Connection is not initialized" |
| 202 | + assert self.cursor is not None, "Cursor is not initialized" |
| 203 | + |
| 204 | + search_param = self.case_config.search_param() # noqa: F841 |
| 205 | + |
| 206 | + try: |
| 207 | + if filters: |
| 208 | + self.cursor.execute(self.select_sql_with_filter, (filters.get("id"), self.vector_to_hex(query), k)) |
| 209 | + else: |
| 210 | + self.cursor.execute(self.select_sql, (self.vector_to_hex(query), k)) |
| 211 | + return [row[0] for row in self.cursor.fetchall()] |
| 212 | + |
| 213 | + except mysql.Error: |
| 214 | + log.exception("Failed to execute search query") |
| 215 | + raise |
0 commit comments