|
| 1 | +from typing import List |
| 2 | + |
| 3 | +from pandas import DataFrame |
| 4 | +from qdrant_client import QdrantClient |
| 5 | +from qdrant_client.http import models |
| 6 | +from sentence_transformers import SentenceTransformer |
| 7 | + |
| 8 | +from mage_ai.io.base import BaseIO |
| 9 | +from mage_ai.io.config import BaseConfigLoader, ConfigKey |
| 10 | + |
| 11 | +DEFAULT_EMBEDDING_MODEL = 'all-MiniLM-L6-v2' |
| 12 | + |
| 13 | + |
| 14 | +class Qdrant(BaseIO): |
| 15 | + def __init__( |
| 16 | + self, |
| 17 | + collection: str, |
| 18 | + path: str = None, |
| 19 | + verbose: bool = True, |
| 20 | + **kwargs,) -> None: |
| 21 | + """ |
| 22 | + Initializes connection to qdrant db. |
| 23 | + """ |
| 24 | + super().__init__(verbose=verbose) |
| 25 | + self.collection = collection |
| 26 | + self.path = path |
| 27 | + self.open() |
| 28 | + |
| 29 | + @classmethod |
| 30 | + def with_config(cls, config: BaseConfigLoader) -> 'Qdrant': |
| 31 | + return cls( |
| 32 | + collection=config[ConfigKey.QDRANT_COLLECTION], |
| 33 | + path=config[ConfigKey.QDRANT_PATH], |
| 34 | + ) |
| 35 | + |
| 36 | + def create_collection( |
| 37 | + self, |
| 38 | + vector_size: int, |
| 39 | + distance: models.Distance = None, |
| 40 | + collection_name: str = None): |
| 41 | + """ |
| 42 | + Create collection in qdrant db. |
| 43 | + Args: |
| 44 | + vector_size (int): dimension size of the vector. |
| 45 | + distance (models.Distance): distance metric to use. |
| 46 | + collection_name (str): name of the collection. |
| 47 | + Defaults to the name defined in io_config.yaml. |
| 48 | + Returns: |
| 49 | + collection created. |
| 50 | + """ |
| 51 | + collection_name = collection_name or self.collection |
| 52 | + distance = distance or models.Distance.COSINE |
| 53 | + return self.client.create_collection( |
| 54 | + collection_name=collection_name, |
| 55 | + vectors_config=models.VectorParams( |
| 56 | + size=vector_size, |
| 57 | + distance=distance), |
| 58 | + ) |
| 59 | + |
| 60 | + def load( |
| 61 | + self, |
| 62 | + limit_results: int, |
| 63 | + query_vector: List, |
| 64 | + collection_name: str = None, |
| 65 | + **kwargs, |
| 66 | + ) -> DataFrame: |
| 67 | + """ |
| 68 | + Loads the data from Qdrant with query_vector. |
| 69 | + Args: |
| 70 | + limit_results (int): Number of results to return. |
| 71 | + query_vector (List): vector list used to query. |
| 72 | + collection_name (str): name of the collection. |
| 73 | + Defaults to the name defined in io_config.yaml. |
| 74 | + Returns: |
| 75 | + DataFrame: Data frame object loaded with data from qdrant |
| 76 | + """ |
| 77 | + # Assume collection is already created and exists. |
| 78 | + collection_name = collection_name or self.collection |
| 79 | + |
| 80 | + hitted_results = self.client.search( |
| 81 | + collection_name=collection_name, |
| 82 | + query_vector=query_vector, |
| 83 | + limit=limit_results, |
| 84 | + with_vectors=True, |
| 85 | + ) |
| 86 | + |
| 87 | + output_df = {} |
| 88 | + output_df['id'] = [hit.id for hit in hitted_results] |
| 89 | + output_df['payload'] = [hit.payload for hit in hitted_results] |
| 90 | + output_df['score'] = [hit.score for hit in hitted_results] |
| 91 | + output_df['vector'] = [hit.vector for hit in hitted_results] |
| 92 | + |
| 93 | + return DataFrame.from_dict(output_df) |
| 94 | + |
| 95 | + def export( |
| 96 | + self, |
| 97 | + df: DataFrame, |
| 98 | + document_column: str, |
| 99 | + id_column: str = None, |
| 100 | + vector_column: str = None, |
| 101 | + collection_name: str = None, |
| 102 | + vector_size: int = None, |
| 103 | + distance: models.Distance = None, |
| 104 | + **kwargs, |
| 105 | + ) -> None: |
| 106 | + """ |
| 107 | + Save data into Qdrant. |
| 108 | + Args: |
| 109 | + df (DataFrame): Data to export. |
| 110 | + document_column (str): Column name containinng documents to export. |
| 111 | + id_column (str): Column name of the id. Default will use index in df. |
| 112 | + vector_column (str): Column name of the vector. Will use default |
| 113 | + encoder to auto generate query vector to auto generate query vector. |
| 114 | + collection_name (str): name of the collection. |
| 115 | + vector_size (int): dimension size of vector. |
| 116 | + distance (models.Distance): distance metric to use. |
| 117 | + """ |
| 118 | + collection_name = collection_name or self.collection |
| 119 | + encoder = SentenceTransformer(DEFAULT_EMBEDDING_MODEL) |
| 120 | + |
| 121 | + try: |
| 122 | + self.client.get_collection(collection_name) |
| 123 | + except ValueError: |
| 124 | + print(f'Creating collection: {collection_name}') |
| 125 | + self.create_collection( |
| 126 | + vector_size=vector_size or encoder.get_sentence_embedding_dimension(), |
| 127 | + distance=distance, |
| 128 | + collection_name=collection_name, |
| 129 | + ) |
| 130 | + |
| 131 | + payloads = df[document_column].tolist() |
| 132 | + if id_column is None: |
| 133 | + ids = [x for x in df.index.tolist()] |
| 134 | + else: |
| 135 | + ids = df[id_column].tolist() |
| 136 | + if vector_column is None: |
| 137 | + vectors = [encoder.encode(str(x)).tolist() for x in payloads] |
| 138 | + else: |
| 139 | + vectors = df[vector_column].tolist() |
| 140 | + |
| 141 | + self.client.upsert( |
| 142 | + collection_name=collection_name, |
| 143 | + points=models.Batch( |
| 144 | + ids=ids, |
| 145 | + payloads=payloads, |
| 146 | + vectors=vectors, |
| 147 | + ), |
| 148 | + ) |
| 149 | + |
| 150 | + def __del__(self): |
| 151 | + self.close() |
| 152 | + |
| 153 | + def __enter__(self): |
| 154 | + self.open() |
| 155 | + return self |
| 156 | + |
| 157 | + def __exit__(self, *args): |
| 158 | + self.close() |
| 159 | + |
| 160 | + def open(self) -> None: |
| 161 | + """ |
| 162 | + Opens an underlying connection to Qdrannt. |
| 163 | + """ |
| 164 | + if self.path is None: |
| 165 | + self.client = QdrantClient(':memory:') |
| 166 | + else: |
| 167 | + self.client = QdrantClient(path=self.path) |
| 168 | + |
| 169 | + def close(self) -> None: |
| 170 | + """ |
| 171 | + Close the underlying connection to Qdrant. |
| 172 | + """ |
| 173 | + self.client.close() |
0 commit comments