|
| 1 | +"""Wrapper around the Clickhouse vector database over VectorDB""" |
| 2 | + |
| 3 | +import io |
| 4 | +import logging |
| 5 | +from contextlib import contextmanager |
| 6 | +from typing import Any |
| 7 | +import clickhouse_connect |
| 8 | +import numpy as np |
| 9 | + |
| 10 | +from ..api import VectorDB, DBCaseConfig |
| 11 | + |
| 12 | +log = logging.getLogger(__name__) |
| 13 | + |
| 14 | +class Clickhouse(VectorDB): |
| 15 | + """Use SQLAlchemy instructions""" |
| 16 | + def __init__( |
| 17 | + self, |
| 18 | + dim: int, |
| 19 | + db_config: dict, |
| 20 | + db_case_config: DBCaseConfig, |
| 21 | + collection_name: str = "CHVectorCollection", |
| 22 | + drop_old: bool = False, |
| 23 | + **kwargs, |
| 24 | + ): |
| 25 | + self.db_config = db_config |
| 26 | + self.case_config = db_case_config |
| 27 | + self.table_name = collection_name |
| 28 | + self.dim = dim |
| 29 | + |
| 30 | + self._index_name = "clickhouse_index" |
| 31 | + self._primary_field = "id" |
| 32 | + self._vector_field = "embedding" |
| 33 | + |
| 34 | + # construct basic units |
| 35 | + self.conn = clickhouse_connect.get_client( |
| 36 | + host=self.db_config["host"], |
| 37 | + port=self.db_config["port"], |
| 38 | + username=self.db_config["user"], |
| 39 | + password=self.db_config["password"], |
| 40 | + database=self.db_config["dbname"]) |
| 41 | + |
| 42 | + if drop_old: |
| 43 | + log.info(f"Clickhouse client drop table : {self.table_name}") |
| 44 | + self._drop_table() |
| 45 | + self._create_table(dim) |
| 46 | + |
| 47 | + self.conn.close() |
| 48 | + self.conn = None |
| 49 | + |
| 50 | + @contextmanager |
| 51 | + def init(self) -> None: |
| 52 | + """ |
| 53 | + Examples: |
| 54 | + >>> with self.init(): |
| 55 | + >>> self.insert_embeddings() |
| 56 | + >>> self.search_embedding() |
| 57 | + """ |
| 58 | + |
| 59 | + self.conn = clickhouse_connect.get_client( |
| 60 | + host=self.db_config["host"], |
| 61 | + port=self.db_config["port"], |
| 62 | + username=self.db_config["user"], |
| 63 | + password=self.db_config["password"], |
| 64 | + database=self.db_config["dbname"]) |
| 65 | + |
| 66 | + try: |
| 67 | + yield |
| 68 | + finally: |
| 69 | + self.conn.close() |
| 70 | + self.conn = None |
| 71 | + |
| 72 | + def _drop_table(self): |
| 73 | + assert self.conn is not None, "Connection is not initialized" |
| 74 | + |
| 75 | + self.conn.command(f'DROP TABLE IF EXISTS {self.db_config["dbname"]}.{self.table_name}') |
| 76 | + |
| 77 | + def _create_table(self, dim: int): |
| 78 | + assert self.conn is not None, "Connection is not initialized" |
| 79 | + |
| 80 | + try: |
| 81 | + # create table |
| 82 | + self.conn.command( |
| 83 | + f'CREATE TABLE IF NOT EXISTS {self.db_config["dbname"]}.{self.table_name} \ |
| 84 | + (id UInt32, embedding Array(Float64)) ENGINE = MergeTree() ORDER BY id;' |
| 85 | + ) |
| 86 | + |
| 87 | + except Exception as e: |
| 88 | + log.warning( |
| 89 | + f"Failed to create Clickhouse table: {self.table_name} error: {e}" |
| 90 | + ) |
| 91 | + raise e from None |
| 92 | + |
| 93 | + def ready_to_load(self): |
| 94 | + pass |
| 95 | + |
| 96 | + def optimize(self, data_size: int | None = None): |
| 97 | + pass |
| 98 | + |
| 99 | + def ready_to_search(self): |
| 100 | + pass |
| 101 | + |
| 102 | + def insert_embeddings( |
| 103 | + self, |
| 104 | + embeddings: list[list[float]], |
| 105 | + metadata: list[int], |
| 106 | + **kwargs: Any, |
| 107 | + ) -> (int, Exception): |
| 108 | + assert self.conn is not None, "Connection is not initialized" |
| 109 | + |
| 110 | + try: |
| 111 | + # do not iterate for bulk insert |
| 112 | + items = [metadata, embeddings] |
| 113 | + |
| 114 | + self.conn.insert(table=self.table_name, data=items, |
| 115 | + column_names=['id', 'embedding'], column_type_names=['UInt32', 'Array(Float64)'], |
| 116 | + column_oriented=True) |
| 117 | + return len(metadata), None |
| 118 | + except Exception as e: |
| 119 | + log.warning(f"Failed to insert data into Clickhouse table ({self.table_name}), error: {e}") |
| 120 | + return 0, e |
| 121 | + |
| 122 | + def search_embedding( |
| 123 | + self, |
| 124 | + query: list[float], |
| 125 | + k: int = 100, |
| 126 | + filters: dict | None = None, |
| 127 | + timeout: int | None = None, |
| 128 | + ) -> list[int]: |
| 129 | + assert self.conn is not None, "Connection is not initialized" |
| 130 | + |
| 131 | + index_param = self.case_config.index_param() |
| 132 | + search_param = self.case_config.search_param() |
| 133 | + |
| 134 | + if filters: |
| 135 | + gt = filters.get("id") |
| 136 | + filterSql = (f'SELECT id, {search_param["metric_type"]}(embedding,{query}) AS score ' |
| 137 | + f'FROM {self.db_config["dbname"]}.{self.table_name} ' |
| 138 | + f'WHERE id > {gt} ' |
| 139 | + f'ORDER BY score LIMIT {k};' |
| 140 | + ) |
| 141 | + result = self.conn.query(filterSql).result_rows |
| 142 | + return [int(row[0]) for row in result] |
| 143 | + else: |
| 144 | + selectSql = (f'SELECT id, {search_param["metric_type"]}(embedding,{query}) AS score ' |
| 145 | + f'FROM {self.db_config["dbname"]}.{self.table_name} ' |
| 146 | + f'ORDER BY score LIMIT {k};' |
| 147 | + ) |
| 148 | + result = self.conn.query(selectSql).result_rows |
| 149 | + return [int(row[0]) for row in result] |
0 commit comments