|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +from typing import List |
| 3 | +import numpy as np |
| 4 | +from redis.commands.search.indexDefinition import IndexDefinition, IndexType |
| 5 | +from redis.commands.search.query import Query |
| 6 | +from redis.commands.search.field import TagField, VectorField, NumericField |
| 7 | +from redis.client import Redis |
| 8 | + |
| 9 | +from modelcache.manager.vector_data.base import VectorBase, VectorData |
| 10 | +from modelcache.utils import import_redis |
| 11 | +from modelcache.utils.log import modelcache_log |
| 12 | +from modelcache.utils.index_util import get_index_name |
| 13 | +from modelcache.utils.index_util import get_index_prefix |
| 14 | +import_redis() |
| 15 | + |
| 16 | + |
| 17 | +class RedisVectorStore(VectorBase): |
| 18 | + def __init__( |
| 19 | + self, |
| 20 | + host: str = "localhost", |
| 21 | + port: str = "6379", |
| 22 | + username: str = "", |
| 23 | + password: str = "", |
| 24 | + dimension: int = 0, |
| 25 | + top_k: int = 1, |
| 26 | + namespace: str = "", |
| 27 | + ): |
| 28 | + if dimension <= 0: |
| 29 | + raise ValueError( |
| 30 | + f"invalid `dim` param: {dimension} in the Milvus vector store." |
| 31 | + ) |
| 32 | + self._client = Redis( |
| 33 | + host=host, port=int(port), username=username, password=password |
| 34 | + ) |
| 35 | + self.top_k = top_k |
| 36 | + self.dimension = dimension |
| 37 | + self.namespace = namespace |
| 38 | + self.doc_prefix = f"{self.namespace}doc:" |
| 39 | + |
| 40 | + def _check_index_exists(self, index_name: str) -> bool: |
| 41 | + """Check if Redis index exists.""" |
| 42 | + try: |
| 43 | + self._client.ft(index_name).info() |
| 44 | + except: |
| 45 | + modelcache_log.info("Index does not exist") |
| 46 | + return False |
| 47 | + modelcache_log.info("Index already exists") |
| 48 | + return True |
| 49 | + |
| 50 | + def create_index(self, index_name, index_prefix): |
| 51 | + dimension = self.dimension |
| 52 | + print('dimension: {}'.format(dimension)) |
| 53 | + if self._check_index_exists(index_name): |
| 54 | + modelcache_log.info( |
| 55 | + "The %s already exists, and it will be used directly", index_name |
| 56 | + ) |
| 57 | + return 'already_exists' |
| 58 | + else: |
| 59 | + id_field_name = "data_id" |
| 60 | + embedding_field_name = "data_vector" |
| 61 | + |
| 62 | + id = NumericField(name=id_field_name) |
| 63 | + embedding = VectorField(embedding_field_name, |
| 64 | + "HNSW", { |
| 65 | + "TYPE": "FLOAT32", |
| 66 | + "DIM": dimension, |
| 67 | + "DISTANCE_METRIC": "L2", |
| 68 | + "INITIAL_CAP": 1000, |
| 69 | + } |
| 70 | + ) |
| 71 | + fields = [id, embedding] |
| 72 | + definition = IndexDefinition(prefix=[index_prefix], index_type=IndexType.HASH) |
| 73 | + |
| 74 | + # create Index |
| 75 | + self._client.ft(index_name).create_index( |
| 76 | + fields=fields, definition=definition |
| 77 | + ) |
| 78 | + return 'create_success' |
| 79 | + |
| 80 | + def mul_add(self, datas: List[VectorData], model=None): |
| 81 | + # pipe = self._client.pipeline() |
| 82 | + for data in datas: |
| 83 | + id: int = data.id |
| 84 | + embedding = data.data.astype(np.float32).tobytes() |
| 85 | + id_field_name = "data_id" |
| 86 | + embedding_field_name = "data_vector" |
| 87 | + obj = {id_field_name: id, embedding_field_name: embedding} |
| 88 | + index_prefix = get_index_prefix(model) |
| 89 | + self._client.hset(f"{index_prefix}{id}", mapping=obj) |
| 90 | + |
| 91 | + def search(self, data: np.ndarray, top_k: int = -1, model=None): |
| 92 | + index_name = get_index_name(model) |
| 93 | + id_field_name = "data_id" |
| 94 | + embedding_field_name = "data_vector" |
| 95 | + |
| 96 | + base_query = f'*=>[KNN 2 @{embedding_field_name} $vector AS distance]' |
| 97 | + query = ( |
| 98 | + Query(base_query) |
| 99 | + .sort_by("distance") |
| 100 | + .return_fields(id_field_name, "distance") |
| 101 | + .dialect(2) |
| 102 | + ) |
| 103 | + |
| 104 | + query_params = {"vector": data.astype(np.float32).tobytes()} |
| 105 | + results = ( |
| 106 | + self._client.ft(index_name) |
| 107 | + .search(query, query_params=query_params) |
| 108 | + .docs |
| 109 | + ) |
| 110 | + return [(float(result.distance), int(getattr(result, id_field_name))) for result in results] |
| 111 | + |
| 112 | + def rebuild(self, ids=None) -> bool: |
| 113 | + pass |
| 114 | + |
| 115 | + def rebuild_col(self, model): |
| 116 | + index_name_model = get_index_name(model) |
| 117 | + if self._check_index_exists(index_name_model): |
| 118 | + try: |
| 119 | + self._client.ft(index_name_model).dropindex(delete_documents=True) |
| 120 | + except Exception as e: |
| 121 | + raise ValueError(str(e)) |
| 122 | + try: |
| 123 | + index_prefix = get_index_prefix(model) |
| 124 | + self.create_index(index_name_model, index_prefix) |
| 125 | + except Exception as e: |
| 126 | + raise ValueError(str(e)) |
| 127 | + return 'rebuild success' |
| 128 | + |
| 129 | + def delete(self, ids) -> None: |
| 130 | + pipe = self._client.pipeline() |
| 131 | + for data_id in ids: |
| 132 | + pipe.delete(f"{self.doc_prefix}{data_id}") |
| 133 | + pipe.execute() |
| 134 | + |
| 135 | + def create(self, model=None): |
| 136 | + index_name = get_index_name(model) |
| 137 | + index_prefix = get_index_prefix(model) |
| 138 | + return self.create_index(index_name, index_prefix) |
| 139 | + |
| 140 | + def get_index_by_name(self, index_name): |
| 141 | + pass |
0 commit comments