"""Index class to add vector indexes on the PGVectorStore.Learn more about vector indexes at https://github.com/pgvector/pgvector?tab=readme-ov-file#indexing"""importenumimportreimportwarningsfromabcimportABC,abstractmethodfromdataclassesimportdataclass,fieldfromtypingimportOptional
[docs]classDistanceStrategy(StrategyMixin,enum.Enum):"""Enumerator of the Distance strategies."""EUCLIDEAN="<->","l2_distance","vector_l2_ops"COSINE_DISTANCE="<=>","cosine_distance","vector_cosine_ops"INNER_PRODUCT="<#>","inner_product","vector_ip_ops"
[docs]defvalidate_identifier(identifier:str)->None:ifre.match(r"^[a-zA-Z_][a-zA-Z0-9_]*$",identifier)isNone:raiseValueError(f"Invalid identifier: {identifier}. Identifiers must start with a letter or underscore, and subsequent characters can be letters, digits, or underscores.")
[docs]@dataclassclassBaseIndex(ABC):""" Abstract base class for defining vector indexes. Attributes: name (Optional[str]): A human-readable name for the index. Defaults to None. index_type (str): A string identifying the type of index. Defaults to "base". distance_strategy (DistanceStrategy): The strategy used to calculate distances between vectors in the index. Defaults to DistanceStrategy.COSINE_DISTANCE. partial_indexes (Optional[list[str]]): A list of names of partial indexes. Defaults to None. extension_name (Optional[str]): The name of the extension to be created for the index, if any. Defaults to None. """name:Optional[str]=Noneindex_type:str="base"distance_strategy:DistanceStrategy=field(default_factory=lambda:DistanceStrategy.COSINE_DISTANCE)partial_indexes:Optional[list[str]]=Noneextension_name:Optional[str]=None
[docs]@abstractmethoddefindex_options(self)->str:"""Set index query options for vector store initialization."""raiseNotImplementedError("index_options method must be implemented by subclass")
def__post_init__(self)->None:"""Check if initialization parameters are valid. Raises: ValueError: extension_name is a valid postgreSQL identifier """ifself.extension_name:validate_identifier(self.extension_name)ifself.index_type:validate_identifier(self.index_type)
[docs]@abstractmethoddefto_parameter(self)->list[str]:"""Convert index attributes to list of configurations."""raiseNotImplementedError("to_parameter method must be implemented by subclass")
[docs]@abstractmethoddefto_string(self)->str:"""Convert index attributes to string."""raiseNotImplementedError("to_string method must be implemented by subclass")
[docs]defindex_options(self)->str:"""Set index query options for vector store initialization."""returnf"(m = {self.m}, ef_construction = {self.ef_construction})"
[docs]defto_parameter(self)->list[str]:"""Convert index attributes to list of configurations."""return[f"hnsw.ef_search = {self.ef_search}"]
[docs]defto_string(self)->str:"""Convert index attributes to string."""warnings.warn("to_string is deprecated, use to_parameter instead.",DeprecationWarning,)returnf"hnsw.ef_search = {self.ef_search}"
[docs]defto_parameter(self)->list[str]:"""Convert index attributes to list of configurations."""return[f"ivfflat.probes = {self.probes}"]
[docs]defto_string(self)->str:"""Convert index attributes to string."""warnings.warn("to_string is deprecated, use to_parameter instead.",DeprecationWarning,)returnf"ivfflat.probes = {self.probes}"