Graph-Native Infrastructure for Context and Accountable AI Systems
Python agent-memoryaiai-governanceai-infrastructureartificial-intelligencecontext-engineeringcontext-graphsdata-engineeringdecision-intelligencedeveloper-toolsexplainable-aigenerative-aigraph-ragknowledge-graphllmontologyprovenancepythonreasoningsemantic-search
docs: Standardize vector_store module with comprehensive algorithms documentation, config, registry, methods, and usage guide
KaifAhmad163c642b747f7
diff --git a/semantica/vector_store/__init__.py b/semantica/vector_store/__init__.pyindex 83da14be..d4fbcc89 100644--- a/semantica/vector_store/__init__.py+++ b/semantica/vector_store/__init__.py@@ -6,6 +6,67 @@ Semantica framework, including support for multiple vector store backends (FAISSPinecone, Weaviate, Qdrant, Milvus), hybrid search combining vector similarity andmetadata filtering, metadata management, and namespace isolation.+Algorithms Used:++Vector Storage Operations:+ - Vector Storage: ID generation (sequential or UUID-based), vector normalization (L2 normalization), batch storage (chunking algorithm), metadata association (vector-to-metadata mapping), vector validation (dimension checking, type validation)+ - Vector Indexing: Index construction (FAISS index types: Flat, IVF, HNSW, PQ), index training (k-means clustering for IVF, graph construction for HNSW), index optimization (index rebuilding, parameter tuning), incremental indexing (add vectors to existing index)+ - Vector Retrieval: Direct vector lookup by ID, batch retrieval, vector-to-metadata mapping+ - Vector Update: In-place vector update, index rebuilding after update, metadata update propagation+ - Vector Deletion: Vector removal, index rebuilding after deletion, metadata cleanup, orphaned metadata detection++Similarity Search Algorithms:+ - Cosine Similarity: Normalized dot product (dot(v1, v2) / (||v1|| * ||v2||)), similarity score calculation (0 to 1 range), top-k selection (argsort with descending order, slice top k)+ - L2 Distance: Euclidean distance calculation (sqrt(sum((v1 - v2)^2))), distance-to-similarity conversion (1 / (1 + distance)), top-k selection+ - Inner Product: Dot product calculation (dot(v1, v2)), unnormalized similarity, top-k selection+ - Approximate Nearest Neighbor (ANN): FAISS IVF (inverted file index with k-means clustering), FAISS HNSW (hierarchical navigable small world graph), FAISS PQ (product quantization for compression), approximate search with configurable accuracy/speed tradeoff+ - k-NN Search: Exact k-nearest neighbors (brute force with full distance calculation), approximate k-NN (using ANN indices), batch k-NN search++Index Construction:+ - FAISS Flat Index: Brute force exact search, no training required, O(n) search time, full vector storage+ - FAISS IVF Index: k-means clustering for cell assignment, inverted file structure, approximate search with configurable nprobe, training on sample vectors+ - FAISS HNSW Index: Hierarchical graph construction (multi-layer graph with connections), greedy search algorithm, approximate search with configurable ef_search, no training required+ - FAISS PQ Index: Product quantization (vector dimension splitting, codebook learning, vector compression), compressed storage, approximate search, training on sample vectors+ - Index Training: k-means clustering (for IVF), codebook learning (for PQ), parameter optimization, training data sampling+ - Index Optimization: Index rebuilding, parameter tuning (nlist for IVF, ef_construction for HNSW, m for PQ), memory optimization++Hybrid Search:+ - Vector Similarity + Metadata Filtering: Metadata filtering first (apply metadata filter conditions), then vector similarity search on filtered set, result combination+ - Result Fusion: Reciprocal Rank Fusion (RRF) algorithm (score = sum(1 / (k + rank)) for each result list, k typically 60), weighted average fusion (weighted sum of scores from multiple sources), result deduplication, top-k selection after fusion+ - Multi-Source Search: Search across multiple vector sources, result collection from each source, fusion using RRF or weighted average, unified result ranking+ - Ranking Strategies: RRF (reciprocal rank fusion with configurable k), weighted average (configurable weights per source), score normalization, result re-ranking++Metadata Management:+ - Metadata Indexing: Field-based indexing (inverted index per field), value-to-vector-ID mapping, list value handling (index each list item), fast lookup O(1) per field-value pair+ - Metadata Filtering: Equality filtering (eq operator), inequality filtering (ne, gt, gte, lt, lte operators), membership filtering (in operator for list values), contains filtering (string/list contains), AND/OR operator combination, condition chaining+ - Schema Management: Schema definition (field types, required fields, default values), schema validation (type checking, required field checking), schema enforcement, schema evolution+ - Metadata Querying: Field-value query (single condition), multi-field query (AND/OR operators), set intersection (AND) or union (OR) operations, result set construction++Namespace Management:+ - Namespace Isolation: Vector-to-namespace mapping (dictionary-based mapping), namespace-based vector organization, namespace-level access control, namespace metadata storage+ - Multi-Tenant Support: Tenant isolation via namespaces, per-namespace configuration, namespace-level statistics, namespace-level operations+ - Access Control: Permission-based access (read, write, delete permissions), entity-to-permission mapping (user/role to permissions), permission checking, access control enforcement+ - Namespace Operations: Namespace creation, namespace deletion, vector addition/removal, namespace metadata management, namespace statistics collection++Adapter Pattern:+ - FAISS Adapter: Local vector storage, FAISS index management, index persistence (save/load), batch operations, multiple index types support+ - Pinecone Adapter: Cloud vector database integration, HTTP API communication, index management, upsert operations, query operations, metadata filtering+ - Weaviate Adapter: GraphQL-based queries, schema management, object-oriented storage, rich metadata support, batch operations+ - Qdrant Adapter: REST API communication, collection management, vector operations, payload (metadata) filtering, batch operations+ - Milvus Adapter: gRPC communication, collection management, vector operations, metadata filtering, batch operations+ - Unified Interface: Common interface for all adapters, backend-specific operation delegation, adapter factory pattern, connection management++Batch Operations:+ - Batch Vector Operations: Chunking algorithm (fixed-size batch creation), batch processing, progress tracking, error handling per batch, retry mechanism+ - Batch Indexing: Batch vector addition to index, incremental index updates, batch index training, batch index optimization+ - Batch Search: Batch query processing, parallel search execution (when supported), result aggregation, batch result formatting++Performance Optimization:+ - Vector Normalization: L2 normalization for cosine similarity, normalization caching, batch normalization+ - Index Optimization: Index parameter tuning, index rebuilding for better performance, memory optimization, search speed optimization+ - Caching: Query result caching, vector caching, metadata caching, cache invalidation strategies+ - Parallel Processing: Batch-level parallelization, multi-threaded search (when supported), concurrent index operations+Key Features:- Multi-backend vector store support (FAISS, Pinecone, Weaviate, Qdrant, Milvus)- Vector indexing and similarity search@@ -14,6 +75,8 @@ Key Features:- Namespace isolation and multi-tenant support- Vector store management and optimization- Batch operations and performance optimization+ - Method registry for extensibility+ - Configuration management with environment variables and config filesMain Classes:- VectorStore: Main vector store interface@@ -29,18 +92,28 @@ Main Classes:- MetadataStore: Metadata indexing and management- NamespaceManager: Namespace isolation and management+Convenience Functions:+ - store_vectors: Store vectors wrapper+ - search_vectors: Search vectors wrapper+ - update_vectors: Update vectors wrapper+ - delete_vectors: Delete vectors wrapper+ - create_index: Create index wrapper+ - hybrid_search: Hybrid search wrapper+ - filter_metadata: Metadata filtering wrapper+ - manage_namespace: Namespace management wrapper+ - get_vector_store_method: Get vector store method by task and name+ - list_available_methods: List registered vector store methods+Example Usage:- >>> from semantica.vector_store import VectorStore, FAISSAdapter+ >>> from semantica.vector_store import VectorStore, store_vectors, search_vectors, hybrid_search+ >>> # Using convenience functions+ >>> vector_ids = store_vectors(vectors, metadata=metadata_list, method="default")+ >>> results = search_vectors(query_vector, k=10, method="default")+ >>> hybrid_results = hybrid_search(query_vector, vectors, metadata, vector_ids, filter=filter, method="default")+ >>> # Using classes directly>>> store = VectorStore(backend="faiss", dimension=768)>>> vector_ids = store.store_vectors(vectors, metadata=metadata_list)>>> results = store.search_vectors(query_vector, k=10)- >>>- >>> from semantica.vector_store import PineconeAdapter- >>> adapter = PineconeAdapter(api_key="your-key")- >>> adapter.connect()- >>> index = adapter.create_index("my-index", dimension=768)- >>> adapter.upsert_vectors(vectors, ids, metadata)- >>>>>> from semantica.vector_store import HybridSearch, MetadataFilter>>> search = HybridSearch()>>> filter = MetadataFilter().eq("category", "science")@@ -108,6 +181,26 @@ from .namespace_manager import (NamespaceManager,Namespace)+from .methods import (+ store_vectors,+ search_vectors,+ update_vectors,+ delete_vectors,+ create_index,+ hybrid_search,+ filter_metadata,+ manage_namespace,+ get_vector_store_method,+ list_available_methods,+)+from .config import (+ VectorStoreConfig,+ vector_store_config,+)+from .registry import (+ MethodRegistry,+ method_registry,+)__all__ = [# Core vector store@@ -151,4 +244,20 @@ __all__ = [# Namespace manager"NamespaceManager","Namespace",+ # Convenience functions+ "store_vectors",+ "search_vectors",+ "update_vectors",+ "delete_vectors",+ "create_index",+ "hybrid_search",+ "filter_metadata",+ "manage_namespace",+ "get_vector_store_method",+ "list_available_methods",+ # Configuration and registry+ "VectorStoreConfig",+ "vector_store_config",+ "MethodRegistry",+ "method_registry",]diff --git a/semantica/vector_store/config.py b/semantica/vector_store/config.pynew file mode 100644index 00000000..07be7945--- /dev/null+++ b/semantica/vector_store/config.py@@ -0,0 +1,227 @@+"""+Configuration Management Module for Vector Store++This module provides centralized configuration management for vector store operations,+supporting multiple configuration sources including environment variables, config files,+and programmatic configuration.++Supported Configuration Sources:+ - Environment variables: VECTOR_STORE_DEFAULT_BACKEND, VECTOR_STORE_DIMENSION, VECTOR_STORE_BATCH_SIZE, etc.+ - Config files: YAML, JSON, TOML formats+ - Programmatic: Python API for setting vector store configurations++Algorithms Used:+ - Environment Variable Parsing: OS-level environment variable access+ - YAML Parsing: YAML parser for configuration file loading+ - JSON Parsing: JSON parser for configuration file loading+ - TOML Parsing: TOML parser for configuration file loading+ - Fallback Chain: Priority-based configuration resolution+ - Dictionary Merging: Deep merge algorithms for configuration updates++Key Features:+ - Environment variable support for vector store parameters+ - Config file support (YAML, JSON, TOML formats)+ - Programmatic configuration via Python API+ - Method-specific configuration management+ - Automatic fallback chain (config file -> environment -> defaults)+ - Global config instance for easy access++Main Classes:+ - VectorStoreConfig: Main configuration manager class for vector store module++Example Usage:+ >>> from semantica.vector_store.config import vector_store_config+ >>> default_backend = vector_store_config.get("default_backend", default="faiss")+ >>> vector_store_config.set("default_backend", "faiss")+ >>> method_config = vector_store_config.get_method_config("store_vectors")+"""++import os+from typing import Optional, Dict, Any+from pathlib import Path++from ..utils.logging import get_logger+++class VectorStoreConfig:+ """Configuration manager for vector store module - supports .env files, environment variables, and programmatic config."""++ def __init__(self, config_file: Optional[str] = None):+ """+ Initialize configuration manager.++ Args:+ config_file: Optional path to configuration file (YAML, JSON, or TOML)+ """+ self.logger = get_logger("vector_store_config")+ self.config_file = config_file+ self._config: Dict[str, Any] = {}+ self._method_configs: Dict[str, Dict[str, Any]] = {}++ # Load configuration+ self._load_config()++ def _load_config(self) -> None:+ """Load configuration from file, environment variables, and defaults."""+ # Load from config file if provided+ if self.config_file:+ self._load_from_file(self.config_file)++ # Load from environment variables+ self._load_from_env()++ # Set defaults+ self._set_defaults()++ def _load_from_file(self, file_path: str) -> None:+ """Load configuration from file."""+ file_path = Path(file_path)+ if not file_path.exists():+ self.logger.warning(f"Config file not found: {file_path}")+ return++ try:+ if file_path.suffix in ['.yaml', '.yml']:+ import yaml+ with open(file_path, 'r') as f:+ config_data = yaml.safe_load(f)+ if config_data and 'vector_store' in config_data:+ self._config.update(config_data['vector_store'])+ elif file_path.suffix == '.json':+ import json+ with open(file_path, 'r') as f:+ config_data = json.load(f)+ if config_data and 'vector_store' in config_data:+ self._config.update(config_data['vector_store'])+ elif file_path.suffix == '.toml':+ import tomli+ with open(file_path, 'rb') as f:+ config_data = tomli.load(f)+ if config_data and 'vector_store' in config_data:+ self._config.update(config_data['vector_store'])+ except Exception as e:+ self.logger.error(f"Failed to load config file: {e}")++ def _load_from_env(self) -> None:+ """Load configuration from environment variables."""+ env_mappings = {+ 'VECTOR_STORE_DEFAULT_BACKEND': 'default_backend',+ 'VECTOR_STORE_DIMENSION': 'dimension',+ 'VECTOR_STORE_BATCH_SIZE': 'batch_size',+ 'VECTOR_STORE_INDEX_TYPE': 'index_type',+ 'VECTOR_STORE_METRIC': 'metric',+ 'VECTOR_STORE_ENABLE_HYBRID_SEARCH': 'enable_hybrid_search',+ 'VECTOR_STORE_NAMESPACE': 'default_namespace',+ 'VECTOR_STORE_FAISS_INDEX_TYPE': 'faiss_index_type',+ 'VECTOR_STORE_PINECONE_API_KEY': 'pinecone_api_key',+ 'VECTOR_STORE_PINECONE_ENVIRONMENT': 'pinecone_environment',+ 'VECTOR_STORE_WEAVIATE_URL': 'weaviate_url',+ 'VECTOR_STORE_QDRANT_URL': 'qdrant_url',+ 'VECTOR_STORE_MILVUS_HOST': 'milvus_host',+ 'VECTOR_STORE_MILVUS_PORT': 'milvus_port',+ }++ for env_var, config_key in env_mappings.items():+ value = os.getenv(env_var)+ if value is not None:+ # Convert string values to appropriate types+ if config_key in ['dimension', 'batch_size', 'milvus_port']:+ try:+ self._config[config_key] = int(value)+ except ValueError:+ self.logger.warning(f"Invalid integer value for {env_var}: {value}")+ elif config_key in ['enable_hybrid_search']:+ self._config[config_key] = value.lower() in ['true', '1', 'yes', 'on']+ else:+ self._config[config_key] = value++ def _set_defaults(self) -> None:+ """Set default configuration values."""+ defaults = {+ 'default_backend': 'faiss',+ 'dimension': 768,+ 'batch_size': 1000,+ 'index_type': 'flat',+ 'metric': 'cosine',+ 'enable_hybrid_search': True,+ 'default_namespace': 'default',+ 'faiss_index_type': 'flat',+ }++ for key, default_value in defaults.items():+ if key not in self._config:+ self._config[key] = default_value++ def get(self, key: str, default: Any = None) -> Any:+ """+ Get configuration value.++ Args:+ key: Configuration key+ default: Default value if key not found++ Returns:+ Configuration value or default+ """+ return self._config.get(key, default)++ def set(self, key: str, value: Any) -> None:+ """+ Set configuration value.++ Args:+ key: Configuration key+ value: Configuration value+ """+ self._config[key] = value++ def update(self, config: Dict[str, Any]) -> None:+ """+ Update configuration with dictionary.++ Args:+ config: Configuration dictionary+ """+ self._config.update(config)++ def get_method_config(self, method_name: str) -> Dict[str, Any]:+ """+ Get method-specific configuration.++ Args:+ method_name: Method name++ Returns:+ Method configuration dictionary+ """+ return self._method_configs.get(method_name, {}).copy()++ def set_method_config(self, method_name: str, config: Dict[str, Any]) -> None:+ """+ Set method-specific configuration.++ Args:+ method_name: Method name+ config: Method configuration dictionary+ """+ self._method_configs[method_name] = config.copy()++ def get_all(self) -> Dict[str, Any]:+ """+ Get all configuration.++ Returns:+ Complete configuration dictionary+ """+ return self._config.copy()++ def reset(self) -> None:+ """Reset configuration to defaults."""+ self._config.clear()+ self._method_configs.clear()+ self._set_defaults()+++# Global configuration instance+vector_store_config = VectorStoreConfig()+diff --git a/semantica/vector_store/methods.py b/semantica/vector_store/methods.pynew file mode 100644index 00000000..cda6f744--- /dev/null+++ b/semantica/vector_store/methods.py@@ -0,0 +1,440 @@+"""+Vector Store Methods Module++This module provides all vector store methods as simple, reusable functions for+storing vectors, searching, indexing, hybrid search, metadata management, and+namespace management. It supports multiple approaches and integrates with the+method registry for extensibility.++Supported Methods:++Vector Storage:+ - "default": Default vector storage using VectorStore+ - "batch": Batch vector storage+ - "normalized": Normalized vector storage++Vector Search:+ - "default": Default vector search+ - "cosine": Cosine similarity search+ - "l2": L2 distance search+ - "inner_product": Inner product search++Index Creation:+ - "default": Default index creation+ - "faiss_flat": FAISS flat index+ - "faiss_ivf": FAISS IVF index+ - "faiss_hnsw": FAISS HNSW index+ - "faiss_pq": FAISS product quantization index++Hybrid Search:+ - "default": Default hybrid search+ - "rrf": Reciprocal rank fusion+ - "weighted": Weighted average fusion++Metadata Management:+ - "default": Default metadata management+ - "indexed": Indexed metadata management+ - "filtered": Filtered metadata management++Namespace Management:+ - "default": Default namespace management+ - "isolated": Isolated namespace management++Algorithms Used:++Vector Storage:+ - ID Generation: Sequential or UUID-based ID generation+ - Vector Normalization: L2 normalization for cosine similarity+ - Batch Processing: Chunking algorithm for large datasets+ - Metadata Association: Vector-to-metadata mapping++Vector Search:+ - Cosine Similarity: Normalized dot product calculation+ - L2 Distance: Euclidean distance calculation+ - Inner Product: Dot product calculation+ - Top-k Selection: Argsort with descending order++Index Creation:+ - FAISS Index Types: Flat, IVF, HNSW, PQ index construction+ - Index Training: k-means clustering, codebook learning+ - Index Optimization: Parameter tuning, index rebuilding++Hybrid Search:+ - Result Fusion: RRF algorithm, weighted average fusion+ - Metadata Filtering: Field-based filtering with operators+ - Multi-Source Search: Cross-source result fusion++Key Features:+ - Multiple vector store operation methods+ - Vector storage with method dispatch+ - Method dispatchers with registry support+ - Custom method registration capability+ - Consistent interface across all methods++Main Functions:+ - store_vectors: Vector storage wrapper+ - search_vectors: Vector search wrapper+ - update_vectors: Vector update wrapper+ - delete_vectors: Vector deletion wrapper+ - create_index: Index creation wrapper+ - hybrid_search: Hybrid search wrapper+ - filter_metadata: Metadata filtering wrapper+ - manage_namespace: Namespace management wrapper+ - get_vector_store_method: Get vector store method by task and name+ - list_available_methods: List registered methods++Example Usage:+ >>> from semantica.vector_store.methods import store_vectors, search_vectors, hybrid_search+ >>> vector_ids = store_vectors(vectors, metadata=metadata_list, method="default")+ >>> results = search_vectors(query_vector, vectors, vector_ids, k=10, method="default")+ >>> hybrid_results = hybrid_search(query_vector, vectors, metadata, vector_ids, filter=filter, method="default")+"""++from typing import Any, Dict, List, Optional, Union+import numpy as np+from .vector_store import VectorStore, VectorIndexer, VectorRetriever, VectorManager+from .hybrid_search import HybridSearch, MetadataFilter, SearchRanker+from .metadata_store import MetadataStore, MetadataIndex, MetadataSchema+from .namespace_manager import NamespaceManager, Namespace+from .registry import method_registry+from .config import vector_store_config++# Global manager instances+_global_store: Optional[VectorStore] = None+_global_hybrid_search: Optional[HybridSearch] = None+_global_metadata_store: Optional[MetadataStore] = None+_global_namespace_manager: Optional[NamespaceManager] = None+++def _get_store() -> VectorStore:+ """Get or create global VectorStore instance."""+ global _global_store+ if _global_store is None:+ config = vector_store_config.get_all()+ backend = config.get('default_backend', 'faiss')+ dimension = config.get('dimension', 768)+ _global_store = VectorStore(backend=backend, config=config, dimension=dimension)+ return _global_store+++def _get_hybrid_search() -> HybridSearch:+ """Get or create global HybridSearch instance."""+ global _global_hybrid_search+ if _global_hybrid_search is None:+ config = vector_store_config.get_all()+ _global_hybrid_search = HybridSearch(**config)+ return _global_hybrid_search+++def _get_metadata_store() -> MetadataStore:+ """Get or create global MetadataStore instance."""+ global _global_metadata_store+ if _global_metadata_store is None:+ config = vector_store_config.get_all()+ _global_metadata_store = MetadataStore(**config)+ return _global_metadata_store+++def _get_namespace_manager() -> NamespaceManager:+ """Get or create global NamespaceManager instance."""+ global _global_namespace_manager+ if _global_namespace_manager is None:+ config = vector_store_config.get_all()+ _global_namespace_manager = NamespaceManager(**config)+ return _global_namespace_manager+++def store_vectors(+ vectors: List[np.ndarray],+ metadata: Optional[List[Dict[str, Any]]] = None,+ method: str = "default",+ **options+) -> List[str]:+ """+ Store vectors in vector store.++ Args:+ vectors: List of vector arrays+ metadata: List of metadata dictionaries+ method: Storage method name (default: "default")+ **options: Additional options++ Returns:+ List of vector IDs+ """+ # Check registry for custom method+ custom_method = method_registry.get("store", method)+ if custom_method:+ return custom_method(vectors, metadata=metadata, **options)++ # Default implementation+ store = _get_store()+ return store.store_vectors(vectors, metadata=metadata, **options)+++def search_vectors(+ query_vector: np.ndarray,+ vectors: Optional[List[np.ndarray]] = None,+ vector_ids: Optional[List[str]] = None,+ k: int = 10,+ method: str = "default",+ **options+) -> List[Dict[str, Any]]:+ """+ Search for similar vectors.++ Args:+ query_vector: Query vector+ vectors: Optional list of vectors to search (uses store vectors if not provided)+ vector_ids: Optional list of vector IDs+ k: Number of results to return+ method: Search method name (default: "default")+ **options: Additional options++ Returns:+ List of search results with scores+ """+ # Check registry for custom method+ custom_method = method_registry.get("search", method)+ if custom_method:+ return custom_method(query_vector, vectors=vectors, vector_ids=vector_ids, k=k, **options)++ # Default implementation+ store = _get_store()+ if vectors is None:+ # Use store's vectors+ return store.search_vectors(query_vector, k=k, **options)+ else:+ # Use provided vectors+ retriever = VectorRetriever(backend=store.backend, **store.config)+ return retriever.search_similar(query_vector, vectors, vector_ids or list(range(len(vectors))), k=k, **options)+++def update_vectors(+ vector_ids: List[str],+ new_vectors: List[np.ndarray],+ method: str = "default",+ **options+) -> bool:+ """+ Update existing vectors.++ Args:+ vector_ids: List of vector IDs to update+ new_vectors: List of new vectors+ method: Update method name (default: "default")+ **options: Additional options++ Returns:+ True if successful+ """+ # Check registry for custom method+ custom_method = method_registry.get("store", method)+ if custom_method:+ return custom_method(vector_ids, new_vectors, **options)++ # Default implementation+ store = _get_store()+ return store.update_vectors(vector_ids, new_vectors, **options)+++def delete_vectors(+ vector_ids: List[str],+ method: str = "default",+ **options+) -> bool:+ """+ Delete vectors from store.++ Args:+ vector_ids: List of vector IDs to delete+ method: Deletion method name (default: "default")+ **options: Additional options++ Returns:+ True if successful+ """+ # Check registry for custom method+ custom_method = method_registry.get("store", method)+ if custom_method:+ return custom_method(vector_ids, **options)++ # Default implementation+ store = _get_store()+ return store.delete_vectors(vector_ids, **options)+++def create_index(+ vectors: List[np.ndarray],+ ids: Optional[List[str]] = None,+ method: str = "default",+ **options+) -> Any:+ """+ Create vector index.++ Args:+ vectors: List of vectors+ ids: Vector IDs+ method: Index creation method name (default: "default")+ **options: Additional options++ Returns:+ Index object+ """+ # Check registry for custom method+ custom_method = method_registry.get("index", method)+ if custom_method:+ return custom_method(vectors, ids=ids, **options)++ # Default implementation+ config = vector_store_config.get_all()+ backend = config.get('default_backend', 'faiss')+ dimension = config.get('dimension', 768)+ indexer = VectorIndexer(backend=backend, dimension=dimension, **config)+ return indexer.create_index(vectors, ids, **options)+++def hybrid_search(+ query_vector: np.ndarray,+ vectors: List[np.ndarray],+ metadata: List[Dict[str, Any]],+ vector_ids: List[str],+ k: int = 10,+ metadata_filter: Optional[MetadataFilter] = None,+ method: str = "default",+ **options+) -> List[Dict[str, Any]]:+ """+ Perform hybrid search combining vector similarity and metadata filtering.++ Args:+ query_vector: Query vector+ vectors: List of vectors to search+ metadata: List of metadata dictionaries+ vector_ids: Vector IDs+ k: Number of results+ metadata_filter: Optional metadata filter+ method: Hybrid search method name (default: "default")+ **options: Additional options++ Returns:+ List of search results+ """+ # Check registry for custom method+ custom_method = method_registry.get("hybrid_search", method)+ if custom_method:+ return custom_method(query_vector, vectors, metadata, vector_ids, k=k, metadata_filter=metadata_filter, **options)++ # Default implementation+ search = _get_hybrid_search()+ return search.search(query_vector, vectors, metadata, vector_ids, k=k, metadata_filter=metadata_filter, **options)+++def filter_metadata(+ metadata: List[Dict[str, Any]],+ filter_conditions: Dict[str, Any],+ operator: str = "AND",+ method: str = "default",+ **options+) -> List[Dict[str, Any]]:+ """+ Filter metadata by conditions.++ Args:+ metadata: List of metadata dictionaries+ filter_conditions: Filter conditions dictionary+ operator: "AND" or "OR" operator+ method: Filtering method name (default: "default")+ **options: Additional options++ Returns:+ Filtered metadata list+ """+ # Check registry for custom method+ custom_method = method_registry.get("metadata", method)+ if custom_method:+ return custom_method(metadata, filter_conditions, operator=operator, **options)++ # Default implementation+ metadata_store = _get_metadata_store()+ # Create filter from conditions+ metadata_filter = MetadataFilter()+ for field, value in filter_conditions.items():+ metadata_filter.eq(field, value)++ # Filter metadata+ filtered = []+ for meta in metadata:+ if metadata_filter.matches(meta):+ filtered.append(meta)++ return filtered+++def manage_namespace(+ namespace_name: str,+ operation: str,+ **options+) -> Any:+ """+ Manage namespace operations.++ Args:+ namespace_name: Namespace name+ operation: Operation type ("create", "delete", "add_vector", "remove_vector", "get_vectors")+ **options: Additional options++ Returns:+ Operation result+ """+ # Check registry for custom method+ custom_method = method_registry.get("namespace", operation)+ if custom_method:+ return custom_method(namespace_name, **options)++ # Default implementation+ manager = _get_namespace_manager()++ if operation == "create":+ return manager.create_namespace(namespace_name, **options)+ elif operation == "delete":+ return manager.delete_namespace(namespace_name, **options)+ elif operation == "add_vector":+ vector_id = options.get("vector_id")+ return manager.add_vector_to_namespace(vector_id, namespace_name, **options)+ elif operation == "remove_vector":+ vector_id = options.get("vector_id")+ return manager.remove_vector_from_namespace(vector_id, namespace_name, **options)+ elif operation == "get_vectors":+ return manager.get_namespace_vectors(namespace_name, **options)+ else:+ raise ValueError(f"Unknown operation: {operation}")+++def get_vector_store_method(task: str, method_name: str) -> Optional[Any]:+ """+ Get vector store method by task and name.++ Args:+ task: Task type (store, search, index, hybrid_search, metadata, namespace)+ method_name: Method name++ Returns:+ Method function or None if not found+ """+ return method_registry.get(task, method_name)+++def list_available_methods(task: Optional[str] = None) -> Dict[str, List[str]]:+ """+ List all available vector store methods.++ Args:+ task: Optional task type to filter by++ Returns:+ Dictionary mapping task types to lists of method names+ """+ return method_registry.list_all(task)+diff --git a/semantica/vector_store/registry.py b/semantica/vector_store/registry.pynew file mode 100644index 00000000..ff9eb920--- /dev/null+++ b/semantica/vector_store/registry.py@@ -0,0 +1,160 @@+"""+Method Registry Module for Vector Store++This module provides a method registry system for registering custom vector store methods,+enabling extensibility and community contributions to the vector store toolkit.++Supported Registration Types:+ - Method Registry: Register custom vector store methods for:+ * "store": Vector storage methods+ * "search": Vector search methods+ * "index": Index creation/management methods+ * "hybrid_search": Hybrid search methods+ * "metadata": Metadata management methods+ * "namespace": Namespace management methods++Algorithms Used:+ - Registry Pattern: Dictionary-based registration and lookup+ - Dynamic Registration: Runtime function registration+ - Type Checking: Type validation for registered components+ - Lookup Algorithms: Hash-based O(1) lookup for methods+ - Task-based Organization: Hierarchical organization by task type++Key Features:+ - Method registry for custom vector store methods+ - Task-based method organization (store, search, index, hybrid_search, metadata, namespace)+ - Dynamic registration and unregistration+ - Easy discovery of available methods+ - Support for community-contributed extensions++Main Classes:+ - MethodRegistry: Registry for custom vector store methods++Global Instances:+ - method_registry: Global method registry instance++Example Usage:+ >>> from semantica.vector_store.registry import method_registry+ >>> method_registry.register("store", "custom_method", custom_store_function)+ >>> available = method_registry.list_all("store")+"""++from typing import Dict, Callable, Any, List, Optional+++class MethodRegistry:+ """Registry for custom vector store methods."""++ def __init__(self):+ """Initialize method registry."""+ self._registry: Dict[str, Dict[str, Callable]] = {+ "store": {},+ "search": {},+ "index": {},+ "hybrid_search": {},+ "metadata": {},+ "namespace": {},+ }++ def register(+ self,+ task: str,+ method_name: str,+ method_func: Callable,+ **metadata+ ) -> None:+ """+ Register a method for a specific task.++ Args:+ task: Task type (store, search, index, hybrid_search, metadata, namespace)+ method_name: Name of the method+ method_func: Method function to register+ **metadata: Additional metadata for the method+ """+ if task not in self._registry:+ raise ValueError(f"Unknown task type: {task}")++ if not callable(method_func):+ raise ValueError("method_func must be callable")++ # Store method with metadata+ method_func._registry_metadata = metadata+ self._registry[task][method_name] = method_func++ def unregister(self, task: str, method_name: str) -> None:+ """+ Unregister a method.++ Args:+ task: Task type+ method_name: Name of the method to unregister+ """+ if task in self._registry and method_name in self._registry[task]:+ del self._registry[task][method_name]++ def get(self, task: str, method_name: str) -> Optional[Callable]:+ """+ Get a registered method.++ Args:+ task: Task type+ method_name: Name of the method++ Returns:+ Method function or None if not found+ """+ if task not in self._registry:+ return None+ return self._registry[task].get(method_name)++ def list_all(self, task: Optional[str] = None) -> Dict[str, List[str]]:+ """+ List all registered methods.++ Args:+ task: Optional task type to filter by++ Returns:+ Dictionary mapping task types to lists of method names+ """+ if task:+ if task in self._registry:+ return {task: list(self._registry[task].keys())}+ return {}++ return {task: list(methods.keys()) for task, methods in self._registry.items()}++ def has(self, task: str, method_name: str) -> bool:+ """+ Check if a method is registered.++ Args:+ task: Task type+ method_name: Name of the method++ Returns:+ True if method is registered, False otherwise+ """+ return task in self._registry and method_name in self._registry[task]++ def get_metadata(self, task: str, method_name: str) -> Dict[str, Any]:+ """+ Get metadata for a registered method.++ Args:+ task: Task type+ method_name: Name of the method++ Returns:+ Method metadata dictionary+ """+ method = self.get(task, method_name)+ if method and hasattr(method, '_registry_metadata'):+ return method._registry_metadata.copy()+ return {}+++# Global method registry instance+method_registry = MethodRegistry()+diff --git a/semantica/vector_store/vector_store_usage.md b/semantica/vector_store/vector_store_usage.mdnew file mode 100644index 00000000..d074b335--- /dev/null+++ b/semantica/vector_store/vector_store_usage.md@@ -0,0 +1,1355 @@+# Vector Store Module Usage Guide++This comprehensive guide demonstrates how to use the vector store module for vector storage and retrieval, supporting multiple vector store backends (FAISS, Pinecone, Weaviate, Qdrant, Milvus), hybrid search combining vector similarity and metadata filtering, metadata management, and namespace isolation.++## Table of Contents++1. [Basic Usage](#basic-usage)+2. [Vector Storage Operations](#vector-storage-operations)+3. [Similarity Search](#similarity-search)+4. [Index Management](#index-management)+5. [Hybrid Search](#hybrid-search)+6. [Metadata Management](#metadata-management)+7. [Namespace Management](#namespace-management)+8. [Store Adapters](#store-adapters)+9. [Algorithms and Methods](#algorithms-and-methods)+10. [Configuration](#configuration)+11. [Advanced Examples](#advanced-examples)++## Basic Usage++### Using VectorStore++```python+from semantica.vector_store import VectorStore+import numpy as np++# Create vector store+store = VectorStore(backend="faiss", dimension=768)++# Store vectors+vectors = [np.random.rand(768) for _ in range(100)]+metadata = [{"category": "science", "year": 2023} for _ in range(100)]+vector_ids = store.store_vectors(vectors, metadata=metadata)++# Search vectors+query_vector = np.random.rand(768)+results = store.search_vectors(query_vector, k=10)++print(f"Stored {len(vector_ids)} vectors")+print(f"Found {len(results)} similar vectors")+```++### Using Convenience Functions++```python+from semantica.vector_store import store_vectors, search_vectors, hybrid_search+from semantica.vector_store import MetadataFilter+import numpy as np++# Store vectors+vectors = [np.random.rand(768) for _ in range(100)]+metadata = [{"category": "science"} for _ in range(100)]+vector_ids = store_vectors(vectors, metadata=metadata, method="default")++# Search vectors+query_vector = np.random.rand(768)+results = search_vectors(query_vector, vectors, vector_ids, k=10, method="default")++# Hybrid search with metadata filter+filter = MetadataFilter().eq("category", "science")+hybrid_results = hybrid_search(+ query_vector, vectors, metadata, vector_ids,+ filter=filter, k=10, method="default"+)++print(f"Found {len(results)} results")+print(f"Found {len(hybrid_results)} hybrid results")+```++### Using HybridSearch++```python+from semantica.vector_store import HybridSearch, MetadataFilter+import numpy as np++# Create hybrid search+search = HybridSearch()++# Create metadata filter+filter = MetadataFilter().eq("category", "science").gt("year", 2020)++# Perform hybrid search+query_vector = np.random.rand(768)+vectors = [np.random.rand(768) for _ in range(1000)]+metadata = [{"category": "science", "year": 2023} for _ in range(1000)]+vector_ids = [f"vec_{i}" for i in range(1000)]++results = search.search(+ query_vector, vectors, metadata, vector_ids,+ filter=filter, k=10+)++print(f"Found {len(results)} results")+for result in results[:5]:+ print(f"ID: {result['id']}, Score: {result['score']:.3f}")+```++## Vector Storage Operations++### Storing Vectors++```python+from semantica.vector_store import VectorStore+import numpy as np++store = VectorStore(backend="faiss", dimension=768)++# Store single batch of vectors+vectors = [np.random.rand(768) for _ in range(1000)]+metadata = [{"category": "science", "year": 2023} for _ in range(1000)]+vector_ids = store.store_vectors(vectors, metadata=metadata)++print(f"Stored {len(vector_ids)} vectors")+print(f"First vector ID: {vector_ids[0]}")+```++### Batch Storage++```python+from semantica.vector_store import VectorStore+import numpy as np++store = VectorStore(backend="faiss", dimension=768)++# Store in batches+batch_size = 100+total_vectors = 10000++for i in range(0, total_vectors, batch_size):+ batch_vectors = [np.random.rand(768) for _ in range(batch_size)]+ batch_metadata = [{"batch": i // batch_size} for _ in range(batch_size)]+ vector_ids = store.store_vectors(batch_vectors, metadata=batch_metadata)+ print(f"Stored batch {i // batch_size + 1}: {len(vector_ids)} vectors")+```++### Updating Vectors++```python+from semantica.vector_store import VectorStore+import numpy as np++store = VectorStore(backend="faiss", dimension=768)++# Store initial vectors+vectors = [np.random.rand(768) for _ in range(100)]+vector_ids = store.store_vectors(vectors)++# Update vectors+new_vectors = [np.random.rand(768) for _ in range(100)]+success = store.update_vectors(vector_ids, new_vectors)++print(f"Updated {len(vector_ids)} vectors: {success}")+```++### Deleting Vectors++```python+from semantica.vector_store import VectorStore+import numpy as np++store = VectorStore(backend="faiss", dimension=768)++# Store vectors+vectors = [np.random.rand(768) for _ in range(100)]+vector_ids = store.store_vectors(vectors)++# Delete some vectors+vectors_to_delete = vector_ids[:10]+success = store.delete_vectors(vectors_to_delete)++print(f"Deleted {len(vectors_to_delete)} vectors: {success}")+```++## Similarity Search++### Basic Similarity Search++```python+from semantica.vector_store import VectorStore+import numpy as np++store = VectorStore(backend="faiss", dimension=768)++# Store vectors+vectors = [np.random.rand(768) for _ in range(1000)]+vector_ids = store.store_vectors(vectors)++# Search for similar vectors+query_vector = np.random.rand(768)+results = store.search_vectors(query_vector, k=10)++print(f"Found {len(results)} similar vectors")+for result in results:+ print(f"ID: {result['id']}, Score: {result['score']:.3f}")+```++### Using VectorRetriever++```python+from semantica.vector_store import VectorRetriever+import numpy as np++retriever = VectorRetriever(backend="faiss")++# Prepare vectors+vectors = [np.random.rand(768) for _ in range(1000)]+vector_ids = [f"vec_{i}" for i in range(1000)]++# Search+query_vector = np.random.rand(768)+results = retriever.search_similar(query_vector, vectors, vector_ids, k=10)++print(f"Found {len(results)} results")+```++### Cosine Similarity Search++```python+from semantica.vector_store import VectorStore+import numpy as np++store = VectorStore(backend="faiss", dimension=768, metric="cosine")++# Store normalized vectors+vectors = [np.random.rand(768) for _ in range(1000)]+# Normalize vectors+vectors = [v / np.linalg.norm(v) for v in vectors]+vector_ids = store.store_vectors(vectors)++# Search+query_vector = np.random.rand(768)+query_vector = query_vector / np.linalg.norm(query_vector)+results = store.search_vectors(query_vector, k=10)++print(f"Cosine similarity results: {len(results)}")+```++### L2 Distance Search++```python+from semantica.vector_store import VectorStore+import numpy as np++store = VectorStore(backend="faiss", dimension=768, metric="l2")++# Store vectors+vectors = [np.random.rand(768) for _ in range(1000)]+vector_ids = store.store_vectors(vectors)++# Search+query_vector = np.random.rand(768)+results = store.search_vectors(query_vector, k=10)++print(f"L2 distance results: {len(results)}")+```++## Index Management++### Creating Indexes++```python+from semantica.vector_store import VectorIndexer+import numpy as np++# Create indexer+indexer = VectorIndexer(backend="faiss", dimension=768)++# Create index+vectors = [np.random.rand(768) for _ in range(1000)]+vector_ids = [f"vec_{i}" for i in range(1000)]+index = indexer.create_index(vectors, vector_ids)++print(f"Created index with {len(vector_ids)} vectors")+```++### FAISS Index Types++```python+from semantica.vector_store import FAISSAdapter+import numpy as np++adapter = FAISSAdapter(dimension=768)++# Create Flat index (exact search)+flat_index = adapter.create_index(index_type="flat", metric="L2")++# Create IVF index (approximate search)+ivf_index = adapter.create_index(+ index_type="ivf",+ metric="L2",+ nlist=100 # Number of clusters+)++# Create HNSW index (approximate search)+hnsw_index = adapter.create_index(+ index_type="hnsw",+ metric="L2",+ m=16, # Number of connections+ ef_construction=200+)++# Create PQ index (compressed)+pq_index = adapter.create_index(+ index_type="pq",+ metric="L2",+ m=8 # Number of sub-vectors+)+```++### Index Training++```python+from semantica.vector_store import FAISSAdapter+import numpy as np++adapter = FAISSAdapter(dimension=768)++# Training vectors+training_vectors = np.random.rand(10000, 768).astype('float32')++# Create and train IVF index+index = adapter.create_index(+ index_type="ivf",+ metric="L2",+ nlist=100+)++# Train index+adapter.train_index(index, training_vectors)++# Add vectors+vectors = np.random.rand(1000, 768).astype('float32')+adapter.add_vectors(index, vectors, ids=[f"vec_{i}" for i in range(1000)])+```++### Index Persistence++```python+from semantica.vector_store import FAISSAdapter+import numpy as np++adapter = FAISSAdapter(dimension=768)++# Create and populate index+index = adapter.create_index(index_type="flat", metric="L2")+vectors = np.random.rand(1000, 768).astype('float32')+adapter.add_vectors(index, vectors, ids=[f"vec_{i}" for i in range(1000)])++# Save index+adapter.save_index(index, "index.faiss")++# Load index+loaded_index = adapter.load_index("index.faiss", dimension=768, index_type="flat")+```++## Hybrid Search++### Basic Hybrid Search++```python+from semantica.vector_store import HybridSearch, MetadataFilter+import numpy as np++search = HybridSearch()++# Prepare data+query_vector = np.random.rand(768)+vectors = [np.random.rand(768) for _ in range(1000)]+metadata = [+ {"category": "science" if i % 2 == 0 else "technology", "year": 2020 + (i % 4)}+ for i in range(1000)+]+vector_ids = [f"vec_{i}" for i in range(1000)]++# Create metadata filter+filter = MetadataFilter().eq("category", "science").gt("year", 2021)++# Perform hybrid search+results = search.search(+ query_vector, vectors, metadata, vector_ids,+ filter=filter, k=10+)++print(f"Found {len(results)} results")+for result in results:+ print(f"ID: {result['id']}, Score: {result['score']:.3f}, Metadata: {result.get('metadata', {})}")+```++### Metadata Filtering++```python+from semantica.vector_store import MetadataFilter++# Create filter with multiple conditions+filter = MetadataFilter() \+ .eq("category", "science") \+ .gt("year", 2020) \+ .in_list("tags", ["AI", "ML"])++# Test metadata+metadata1 = {"category": "science", "year": 2023, "tags": ["AI", "ML"]}+metadata2 = {"category": "technology", "year": 2023, "tags": ["AI"]}++print(f"Metadata1 matches: {filter.matches(metadata1)}") # True+print(f"Metadata2 matches: {filter.matches(metadata2)}") # False+```++### Result Fusion++```python+from semantica.vector_store import SearchRanker+import numpy as np++ranker = SearchRanker(strategy="reciprocal_rank_fusion")++# Multiple result lists+results1 = [+ {"id": "vec_1", "score": 0.9},+ {"id": "vec_2", "score": 0.8},+ {"id": "vec_3", "score": 0.7}+]+results2 = [+ {"id": "vec_2", "score": 0.85},+ {"id": "vec_4", "score": 0.75},+ {"id": "vec_1", "score": 0.7}+]++# Fuse results using RRF+fused = ranker.rank([results1, results2], k=60)++print(f"Fused {len(fused)} results")+for result in fused:+ print(f"ID: {result['id']}, Score: {result['score']:.3f}")+```++### Multi-Source Search++```python+from semantica.vector_store import HybridSearch+import numpy as np++search = HybridSearch()++# Multiple sources+sources = [+ {+ "vectors": [np.random.rand(768) for _ in range(500)],+ "metadata": [{"source": "db1"} for _ in range(500)],+ "ids": [f"db1_vec_{i}" for i in range(500)]+ },+ {+ "vectors": [np.random.rand(768) for _ in range(500)],+ "metadata": [{"source": "db2"} for _ in range(500)],+ "ids": [f"db2_vec_{i}" for i in range(500)]+ }+]++# Search across all sources+query_vector = np.random.rand(768)+results = search.multi_source_search(query_vector, sources, k=10)++print(f"Found {len(results)} results from multiple sources")+```++## Metadata Management++### Storing Metadata++```python+from semantica.vector_store import MetadataStore++store = MetadataStore()++# Store metadata+store.store_metadata("vec_1", {"category": "science", "year": 2023, "tags": ["AI"]})+store.store_metadata("vec_2", {"category": "technology", "year": 2022, "tags": ["ML"]})++# Get metadata+metadata = store.get_metadata("vec_1")+print(f"Metadata: {metadata}")+```++### Metadata Indexing++```python+from semantica.vector_store import MetadataIndex++index = MetadataIndex()++# Index metadata+index.index_metadata("vec_1", {"category": "science", "year": 2023})+index.index_metadata("vec_2", {"category": "science", "year": 2022})+index.index_metadata("vec_3", {"category": "technology", "year": 2023})++# Query by metadata+matching_ids = index.query({"category": "science"}, operator="AND")+print(f"Found {len(matching_ids)} vectors with category='science'")++# Query with multiple conditions+matching_ids = index.query({"category": "science", "year": 2023}, operator="AND")+print(f"Found {len(matching_ids)} vectors matching both conditions")+```++### Metadata Schema++```python+from semantica.vector_store import MetadataSchema++# Define schema+schema = MetadataSchema({+ "category": {"type": str, "required": True},+ "year": {"type": int, "required": True},+ "tags": {"type": list, "required": False}+})++# Validate metadata+metadata1 = {"category": "science", "year": 2023, "tags": ["AI"]}+metadata2 = {"category": "science"} # Missing required field++print(f"Metadata1 valid: {schema.validate(metadata1)}") # True+try:+ schema.validate(metadata2) # Raises ValidationError+except Exception as e:+ print(f"Metadata2 invalid: {e}")+```++### Metadata Querying++```python+from semantica.vector_store import MetadataStore++store = MetadataStore()++# Store metadata+for i in range(100):+ store.store_metadata(+ f"vec_{i}",+ {+ "category": "science" if i % 2 == 0 else "technology",+ "year": 2020 + (i % 4),+ "tags": ["AI"] if i % 3 == 0 else ["ML"]+ }+ )++# Query metadata+vector_ids = store.query_metadata({"category": "science"}, operator="AND")+print(f"Found {len(vector_ids)} vectors with category='science'")++# Query with OR operator+vector_ids = store.query_metadata({"category": "science", "tags": "AI"}, operator="OR")+print(f"Found {len(vector_ids)} vectors matching any condition")+```++## Namespace Management++### Creating Namespaces++```python+from semantica.vector_store import NamespaceManager++manager = NamespaceManager()++# Create namespace+namespace = manager.create_namespace(+ "user1",+ description="User 1 vectors",+ metadata={"owner": "user1", "created": "2024-01-01"}+)++print(f"Created namespace: {namespace.name}")+print(f"Description: {namespace.description}")+```++### Adding Vectors to Namespaces++```python+from semantica.vector_store import NamespaceManager++manager = NamespaceManager()++# Create namespace+manager.create_namespace("user1", description="User 1 vectors")++# Add vectors to namespace+for i in range(100):+ manager.add_vector_to_namespace(f"vec_{i}", "user1")++# Get namespace vectors+vectors = manager.get_namespace_vectors("user1")+print(f"Namespace 'user1' has {len(vectors)} vectors")+```++### Access Control++```python+from semantica.vector_store import NamespaceManager++manager = NamespaceManager()++# Create namespace+namespace = manager.create_namespace("docs", description="Document vectors")++# Set access control+namespace.set_access_control("user1", ["read", "write"])+namespace.set_access_control("user2", ["read"])++# Check permissions+has_read = namespace.has_permission("user1", "read")+has_write = namespace.has_permission("user2", "write")++print(f"User1 has read: {has_read}, write: {has_write}")+print(f"User2 has read: {namespace.has_permission('user2', 'read')}")+print(f"User2 has write: {namespace.has_permission('user2', 'write')}")+```++### Multi-Tenant Support++```python+from semantica.vector_store import NamespaceManager++manager = NamespaceManager()++# Create namespaces for different tenants+manager.create_namespace("tenant1", description="Tenant 1 vectors")+manager.create_namespace("tenant2", description="Tenant 2 vectors")++# Add vectors to each tenant+for i in range(50):+ manager.add_vector_to_namespace(f"t1_vec_{i}", "tenant1")+ manager.add_vector_to_namespace(f"t2_vec_{i}", "tenant2")++# Get tenant-specific vectors+tenant1_vectors = manager.get_namespace_vectors("tenant1")+tenant2_vectors = manager.get_namespace_vectors("tenant2")++print(f"Tenant1: {len(tenant1_vectors)} vectors")+print(f"Tenant2: {len(tenant2_vectors)} vectors")+```++## Store Adapters++### FAISS Adapter++```python+from semantica.vector_store import FAISSAdapter+import numpy as np++# Create FAISS adapter+adapter = FAISSAdapter(dimension=768)++# Create index+index = adapter.create_index(index_type="flat", metric="L2")++# Add vectors+vectors = np.random.rand(1000, 768).astype('float32')+ids = [f"vec_{i}" for i in range(1000)]+adapter.add_vectors(index, vectors, ids=ids)++# Search+query_vector = np.random.rand(768).astype('float32')+distances, indices = adapter.search(index, query_vector, k=10)++print(f"Found {len(indices)} similar vectors")+```++### Pinecone Adapter++```python+from semantica.vector_store import PineconeAdapter+import numpy as np++# Create Pinecone adapter+adapter = PineconeAdapter(api_key="your-api-key", environment="us-west1-gcp")++# Connect+adapter.connect()++# Create index+index = adapter.create_index("my-index", dimension=768, metric="cosine")++# Upsert vectors+vectors = [np.random.rand(768).tolist() for _ in range(100)]+ids = [f"vec_{i}" for i in range(100)]+metadata = [{"category": "science"} for _ in range(100)]+adapter.upsert_vectors(vectors, ids, metadata)++# Query+query_vector = np.random.rand(768).tolist()+results = adapter.query_vectors(query_vector, top_k=10, include_metadata=True)++print(f"Found {len(results)} results")+```++### Weaviate Adapter++```python+from semantica.vector_store import WeaviateAdapter+import numpy as np++# Create Weaviate adapter+adapter = WeaviateAdapter(url="http://localhost:8080")++# Connect+adapter.connect()++# Create schema+adapter.create_schema(+ "Document",+ properties=[{"name": "text", "dataType": "text"}]+)++# Add objects with vectors+objects = [{"text": f"Document {i}"} for i in range(100)]+vectors = [np.random.rand(768).tolist() for _ in range(100)]+object_ids = adapter.add_objects(objects, vectors=vectors)++# Query+query_vector = np.random.rand(768).tolist()+results = adapter.query_vectors(+ query_vector,+ limit=10,+ where={"category": "science"}+)++print(f"Found {len(results)} results")+```++### Qdrant Adapter++```python+from semantica.vector_store import QdrantAdapter+import numpy as np++# Create Qdrant adapter+adapter = QdrantAdapter(url="http://localhost:6333")++# Connect+adapter.connect()++# Create collection+collection = adapter.create_collection("my-collection", dimension=768)++# Upsert vectors+vectors = [np.random.rand(768).tolist() for _ in range(100)]+ids = [f"vec_{i}" for i in range(100)]+payloads = [{"category": "science"} for _ in range(100)]+adapter.upsert_vectors(collection, vectors, ids, payloads)++# Search+query_vector = np.random.rand(768).tolist()+results = adapter.search(+ collection,+ query_vector,+ top=10,+ query_filter={"must": [{"key": "category", "match": {"value": "science"}}]}+)++print(f"Found {len(results)} results")+```++### Milvus Adapter++```python+from semantica.vector_store import MilvusAdapter+import numpy as np++# Create Milvus adapter+adapter = MilvusAdapter(host="localhost", port="19530")++# Connect+adapter.connect()++# Create collection+collection = adapter.create_collection(+ "my-collection",+ dimension=768,+ metric_type="L2"+)++# Insert vectors+vectors = np.random.rand(100, 768).astype('float32')+ids = [f"vec_{i}" for i in range(100)]+adapter.insert_vectors(collection, vectors, ids)++# Search+query_vector = np.random.rand(768).astype('float32')+results = adapter.search(collection, query_vector, top_k=10)++print(f"Found {len(results)} results")+```++## Algorithms and Methods++### Vector Storage Algorithms++#### Vector Storage+**Algorithm**: ID generation and vector normalization++1. **ID Generation**: Generate unique IDs (sequential: vec_0, vec_1, ... or UUID-based)+2. **Vector Normalization**: Optional L2 normalization (v / ||v||) for cosine similarity+3. **Metadata Association**: Map vector IDs to metadata dictionaries+4. **Index Update**: Update vector index after storage++**Time Complexity**: O(n) where n = number of vectors+**Space Complexity**: O(n × d) where d = vector dimension++```python+# Vector storage+vector_ids = store.store_vectors(vectors, metadata=metadata_list)+```++#### Batch Storage+**Algorithm**: Chunking algorithm for large datasets++1. **Batch Creation**: Divide vectors into fixed-size batches+2. **Batch Processing**: Process each batch sequentially+3. **Progress Tracking**: Track stored count, progress percentage+4. **Error Handling**: Handle errors per batch, continue on failure++**Time Complexity**: O(n) where n = total vectors+**Space Complexity**: O(b × d) where b = batch size, d = dimension++### Similarity Search Algorithms++#### Cosine Similarity+**Algorithm**: Normalized dot product calculation++1. **Vector Normalization**: Normalize query and database vectors (L2 norm)+2. **Dot Product**: Calculate dot(v1, v2) for all vectors+3. **Similarity Score**: Similarity = dot(v1, v2) / (||v1|| × ||v2||)+4. **Top-k Selection**: Argsort similarities in descending order, select top k++**Time Complexity**: O(n × d) where n = vectors, d = dimension+**Space Complexity**: O(n) for similarities++```python+# Cosine similarity search+results = store.search_vectors(query_vector, k=10)+```++#### L2 Distance+**Algorithm**: Euclidean distance calculation++1. **Distance Calculation**: distance = sqrt(sum((v1 - v2)²))+2. **Distance-to-Similarity**: similarity = 1 / (1 + distance)+3. **Top-k Selection**: Argsort distances in ascending order, select top k++**Time Complexity**: O(n × d) where n = vectors, d = dimension+**Space Complexity**: O(n) for distances++#### Approximate Nearest Neighbor (ANN)+**Algorithm**: FAISS approximate search algorithms++**FAISS IVF**:+1. **k-means Clustering**: Cluster vectors into nlist cells+2. **Inverted File**: Build inverted file mapping cells to vectors+3. **Approximate Search**: Search nprobe cells, compute exact distances within cells++**FAISS HNSW**:+1. **Graph Construction**: Build multi-layer graph with connections+2. **Greedy Search**: Start from entry point, traverse graph to nearest neighbors+3. **Approximate Search**: Configurable ef_search for accuracy/speed tradeoff++**Time Complexity**: O(log n) to O(n) depending on index type and parameters+**Space Complexity**: O(n × d) for vectors, O(n × m) for HNSW graph++```python+# ANN search with FAISS+adapter = FAISSAdapter(dimension=768)+index = adapter.create_index(index_type="ivf", nlist=100)+results = adapter.search(index, query_vector, k=10)+```++### Index Construction Algorithms++#### FAISS Flat Index+**Algorithm**: Brute force exact search++1. **No Training**: Direct vector storage, no preprocessing+2. **Exact Search**: Compute all distances, select top k+3. **Full Storage**: Store all vectors in memory++**Time Complexity**: O(n × d) for search+**Space Complexity**: O(n × d) for storage++#### FAISS IVF Index+**Algorithm**: Inverted file index with k-means++1. **Training**: k-means clustering on training vectors (nlist clusters)+2. **Cell Assignment**: Assign each vector to nearest cluster center+3. **Inverted File**: Build mapping from cluster to vectors+4. **Search**: Search nprobe clusters, compute exact distances++**Time Complexity**: O(n × d × log(nlist)) for training, O(nprobe × (n/nlist) × d) for search+**Space Complexity**: O(n × d) for vectors, O(nlist × d) for cluster centers++#### FAISS HNSW Index+**Algorithm**: Hierarchical navigable small world graph++1. **Graph Construction**: Build multi-layer graph (m connections per node)+2. **Layer Assignment**: Assign vectors to layers probabilistically+3. **Greedy Search**: Start from entry point, traverse graph greedily+4. **Connection Management**: Maintain connections to nearest neighbors++**Time Complexity**: O(log n) for search with ef_search parameter+**Space Complexity**: O(n × m) for graph connections++### Hybrid Search Algorithms++#### Vector Similarity + Metadata Filtering+**Algorithm**: Two-stage filtering and search++1. **Metadata Filtering**: Apply metadata filter conditions first+2. **Vector Search**: Perform vector similarity search on filtered set+3. **Result Combination**: Combine filtered metadata with search results++**Time Complexity**: O(m × f) for filtering + O(n × d) for search where m = metadata count, f = filter conditions, n = filtered vectors+**Space Complexity**: O(n) for filtered vectors++```python+# Hybrid search+filter = MetadataFilter().eq("category", "science")+results = hybrid_search(query_vector, vectors, metadata, vector_ids, filter=filter, k=10)+```++#### Reciprocal Rank Fusion (RRF)+**Algorithm**: Result fusion using reciprocal ranks++1. **Rank Collection**: Collect ranks of each result from all result lists+2. **Score Calculation**: score = sum(1 / (k + rank)) for each result across all lists+3. **Result Ranking**: Sort results by RRF score in descending order+4. **Top-k Selection**: Select top k results after fusion++**Time Complexity**: O(r × l) where r = results per list, l = number of lists+**Space Complexity**: O(r × l) for result storage++```python+# RRF fusion+ranker = SearchRanker(strategy="reciprocal_rank_fusion")+fused = ranker.rank([results1, results2], k=60)+```++#### Weighted Average Fusion+**Algorithm**: Weighted sum of scores++1. **Score Collection**: Collect scores for each result from all lists+2. **Weighted Sum**: weighted_score = sum(score × weight) for each result+3. **Result Ranking**: Sort results by weighted score+4. **Top-k Selection**: Select top k results++**Time Complexity**: O(r × l) where r = results per list, l = number of lists+**Space Complexity**: O(r × l) for result storage++### Metadata Management Algorithms++#### Metadata Indexing+**Algorithm**: Inverted index per field++1. **Field Indexing**: Create inverted index for each metadata field+2. **Value Mapping**: Map field values to sets of vector IDs+3. **List Handling**: Index each item in list values+4. **Fast Lookup**: O(1) lookup per field-value pair++**Time Complexity**: O(m × f) where m = metadata count, f = fields per metadata+**Space Complexity**: O(m × f) for indexes++```python+# Metadata indexing+index = MetadataIndex()+index.index_metadata("vec_1", {"category": "science", "year": 2023})+matching_ids = index.query({"category": "science"})+```++#### Metadata Filtering+**Algorithm**: Condition-based filtering++1. **Condition Evaluation**: Evaluate each filter condition (eq, ne, gt, gte, lt, lte, in, contains)+2. **AND/OR Combination**: Combine conditions using AND (intersection) or OR (union)+3. **Result Set Construction**: Build set of matching vector IDs++**Time Complexity**: O(m × c) where m = metadata count, c = conditions+**Space Complexity**: O(m) for result set++```python+# Metadata filtering+filter = MetadataFilter().eq("category", "science").gt("year", 2020)+matching = [meta for meta in metadata if filter.matches(meta)]+```++### Namespace Management Algorithms++#### Namespace Isolation+**Algorithm**: Vector-to-namespace mapping++1. **Mapping Storage**: Dictionary mapping vector_id -> namespace+2. **Namespace Organization**: Group vectors by namespace+3. **Access Control**: Store permissions per namespace-entity pair+4. **Isolation Enforcement**: Filter operations by namespace++**Time Complexity**: O(1) for vector-to-namespace lookup+**Space Complexity**: O(n) where n = vectors++```python+# Namespace isolation+manager.add_vector_to_namespace("vec_1", "user1")+vectors = manager.get_namespace_vectors("user1")+```++### Methods++#### VectorStore Methods++- `store_vectors(vectors, metadata, **options)`: Store vectors with metadata+- `search_vectors(query_vector, k, **options)`: Search for similar vectors+- `update_vectors(vector_ids, new_vectors, **options)`: Update existing vectors+- `delete_vectors(vector_ids, **options)`: Delete vectors+- `get_vector(vector_id)`: Get vector by ID+- `get_metadata(vector_id)`: Get metadata by vector ID++#### VectorIndexer Methods++- `create_index(vectors, ids, **options)`: Create vector index+- `update_index(index, new_vectors, **options)`: Update existing index+- `optimize_index(index, **options)`: Optimize index for performance++#### VectorRetriever Methods++- `search_similar(query_vector, vectors, ids, k, **options)`: Search for similar vectors+- `search_by_metadata(metadata_filters, vectors, metadata, **options)`: Search by metadata+- `search_hybrid(query_vector, metadata_filters, vectors, metadata, **options)`: Hybrid search++#### HybridSearch Methods++- `search(query_vector, vectors, metadata, vector_ids, k, metadata_filter, **options)`: Perform hybrid search+- `multi_source_search(query_vector, sources, k, **options)`: Search across multiple sources+- `filter_by_metadata(results, metadata_filter)`: Filter results by metadata++#### MetadataStore Methods++- `store_metadata(vector_id, metadata)`: Store metadata for vector+- `get_metadata(vector_id)`: Get metadata for vector+- `query_metadata(conditions, operator)`: Query vectors by metadata conditions+- `update_metadata(vector_id, metadata)`: Update metadata+- `delete_metadata(vector_id)`: Delete metadata++#### NamespaceManager Methods++- `create_namespace(name, description, metadata, **options)`: Create namespace+- `delete_namespace(name)`: Delete namespace+- `add_vector_to_namespace(vector_id, namespace_name)`: Add vector to namespace+- `remove_vector_from_namespace(vector_id, namespace_name)`: Remove vector from namespace+- `get_namespace_vectors(namespace_name)`: Get all vectors in namespace+- `get_namespace(namespace_name)`: Get namespace object++#### Convenience Functions++- `store_vectors(vectors, metadata, method, **options)`: Store vectors wrapper+- `search_vectors(query_vector, vectors, vector_ids, k, method, **options)`: Search vectors wrapper+- `update_vectors(vector_ids, new_vectors, method, **options)`: Update vectors wrapper+- `delete_vectors(vector_ids, method, **options)`: Delete vectors wrapper+- `create_index(vectors, ids, method, **options)`: Create index wrapper+- `hybrid_search(query_vector, vectors, metadata, vector_ids, k, metadata_filter, method, **options)`: Hybrid search wrapper+- `filter_metadata(metadata, filter_conditions, operator, method, **options)`: Filter metadata wrapper+- `manage_namespace(namespace_name, operation, **options)`: Namespace management wrapper++## Configuration++### Environment Variables++```bash+# Vector store configuration+export VECTOR_STORE_DEFAULT_BACKEND=faiss+export VECTOR_STORE_DIMENSION=768+export VECTOR_STORE_BATCH_SIZE=1000+export VECTOR_STORE_INDEX_TYPE=flat+export VECTOR_STORE_METRIC=cosine+export VECTOR_STORE_ENABLE_HYBRID_SEARCH=true+export VECTOR_STORE_NAMESPACE=default++# FAISS configuration+export VECTOR_STORE_FAISS_INDEX_TYPE=flat++# Pinecone configuration+export VECTOR_STORE_PINECONE_API_KEY=your-api-key+export VECTOR_STORE_PINECONE_ENVIRONMENT=us-west1-gcp++# Weaviate configuration+export VECTOR_STORE_WEAVIATE_URL=http://localhost:8080++# Qdrant configuration+export VECTOR_STORE_QDRANT_URL=http://localhost:6333++# Milvus configuration+export VECTOR_STORE_MILVUS_HOST=localhost+export VECTOR_STORE_MILVUS_PORT=19530+```++### Programmatic Configuration++```python+from semantica.vector_store.config import vector_store_config++# Get configuration+backend = vector_store_config.get("default_backend", default="faiss")+dimension = vector_store_config.get("dimension", default=768)++# Set configuration+vector_store_config.set("default_backend", "faiss")+vector_store_config.set("dimension", 768)++# Update with dictionary+vector_store_config.update({+ "default_backend": "faiss",+ "dimension": 768,+ "batch_size": 1000+})+```++### Configuration File (YAML)++```yaml+# config.yaml+vector_store:+ default_backend: faiss+ dimension: 768+ batch_size: 1000+ index_type: flat+ metric: cosine+ enable_hybrid_search: true+ default_namespace: default+ faiss_index_type: flat+ pinecone_api_key: your-api-key+ pinecone_environment: us-west1-gcp+ weaviate_url: http://localhost:8080+ qdrant_url: http://localhost:6333+ milvus_host: localhost+ milvus_port: 19530+```++## Advanced Examples++### Complete Vector Store Pipeline++```python+from semantica.vector_store import (+ VectorStore,+ HybridSearch,+ MetadataFilter,+ store_vectors,+ search_vectors,+ hybrid_search+)+import numpy as np++# 1. Create vector store+store = VectorStore(backend="faiss", dimension=768)++# 2. Generate and store vectors+vectors = [np.random.rand(768) for _ in range(10000)]+metadata = [+ {"category": "science" if i % 2 == 0 else "technology", "year": 2020 + (i % 4)}+ for i in range(10000)+]+vector_ids = store_vectors(vectors, metadata=metadata)++# 3. Create metadata filter+filter = MetadataFilter().eq("category", "science").gt("year", 2021)++# 4. Perform hybrid search+query_vector = np.random.rand(768)+results = hybrid_search(+ query_vector, vectors, metadata, vector_ids,+ filter=filter, k=10+)++print(f"Stored {len(vector_ids)} vectors")+print(f"Found {len(results)} hybrid search results")+```++### Multi-Backend Vector Store++```python+from semantica.vector_store import FAISSAdapter, PineconeAdapter+import numpy as np++# Local FAISS store+faiss_adapter = FAISSAdapter(dimension=768)+faiss_index = faiss_adapter.create_index(index_type="flat", metric="L2")+faiss_vectors = np.random.rand(1000, 768).astype('float32')+faiss_adapter.add_vectors(faiss_index, faiss_vectors, ids=[f"faiss_{i}" for i in range(1000)])++# Cloud Pinecone store+pinecone_adapter = PineconeAdapter(api_key="your-key")+pinecone_adapter.connect()+pinecone_index = pinecone_adapter.create_index("my-index", dimension=768)+pinecone_vectors = [np.random.rand(768).tolist() for _ in range(1000)]+pinecone_adapter.upsert_vectors(pinecone_vectors, [f"pinecone_{i}" for i in range(1000)])++# Search both+query_vector = np.random.rand(768)+faiss_results = faiss_adapter.search(faiss_index, query_vector, k=10)+pinecone_results = pinecone_adapter.query_vectors(query_vector, top_k=10)+```++### Hybrid Search with Custom Ranking++```python+from semantica.vector_store import HybridSearch, SearchRanker, MetadataFilter+import numpy as np++# Create hybrid search with custom ranker+ranker = SearchRanker(strategy="weighted_average")+search = HybridSearch(ranking_strategy="weighted_average")++# Prepare data+query_vector = np.random.rand(768)+vectors = [np.random.rand(768) for _ in range(1000)]+metadata = [{"category": "science", "year": 2023} for _ in range(1000)]+vector_ids = [f"vec_{i}" for i in range(1000)]++# Create filter+filter = MetadataFilter().eq("category", "science")++# Perform search+results = search.search(+ query_vector, vectors, metadata, vector_ids,+ filter=filter, k=10+)++# Custom ranking with weights+results1 = search.search(query_vector, vectors[:500], metadata[:500], vector_ids[:500], k=10)+results2 = search.search(query_vector, vectors[500:], metadata[500:], vector_ids[500:], k=10)++fused = ranker.rank([results1, results2], weights=[0.7, 0.3])+print(f"Fused {len(fused)} results with weighted average")+```++### Namespace-Based Multi-Tenant System++```python+from semantica.vector_store import NamespaceManager, VectorStore+import numpy as np++# Create namespace manager+namespace_manager = NamespaceManager()++# Create namespaces for tenants+namespace_manager.create_namespace("tenant1", description="Tenant 1")+namespace_manager.create_namespace("tenant2", description="Tenant 2")++# Create vector store+store = VectorStore(backend="faiss", dimension=768)++# Store vectors for each tenant+for tenant in ["tenant1", "tenant2"]:+ vectors = [np.random.rand(768) for _ in range(1000)]+ vector_ids = store.store_vectors(vectors)++ # Add to namespace+ for vec_id in vector_ids:+ namespace_manager.add_vector_to_namespace(vec_id, tenant)++# Tenant-specific search+tenant1_vectors = namespace_manager.get_namespace_vectors("tenant1")+query_vector = np.random.rand(768)+# Search only tenant1 vectors+results = store.search_vectors(query_vector, k=10)+tenant1_results = [r for r in results if r['id'] in tenant1_vectors]+```++### Custom Method Registration++```python+from semantica.vector_store.registry import method_registry+from semantica.vector_store import store_vectors++# Register custom store method+def custom_store_vectors(vectors, metadata=None, **options):+ # Custom logic (e.g., normalization)+ import numpy as np+ normalized_vectors = [v / np.linalg.norm(v) for v in vectors]+ # Call default implementation+ from semantica.vector_store.methods import _get_store+ store = _get_store()+ return store.store_vectors(normalized_vectors, metadata=metadata, **options)++method_registry.register("store", "normalized", custom_store_vectors)++# Use custom method+vector_ids = store_vectors(vectors, metadata=metadata, method="normalized")+```++## Best Practices++1. **Vector Storage**:+ - Normalize vectors for cosine similarity+ - Use batch operations for large datasets+ - Associate metadata at storage time+ - Validate vector dimensions before storage++2. **Similarity Search**:+ - Choose appropriate metric (cosine for normalized, L2 for distance)+ - Use approximate indices (IVF, HNSW) for large datasets+ - Set appropriate k value (not too large)+ - Cache query vectors when possible++3. **Index Management**:+ - Train indices on representative data+ - Choose index type based on dataset size and accuracy requirements+ - Optimize index parameters (nlist for IVF, m for HNSW)+ - Persist indices for reuse++4. **Hybrid Search**:+ - Apply metadata filters before vector search for efficiency+ - Use RRF for multi-source fusion+ - Tune ranking parameters (k for RRF, weights for weighted average)+ - Combine complementary filters++5. **Metadata Management**:+ - Index frequently queried fields+ - Use schema validation for data quality+ - Keep metadata consistent with vectors+ - Use appropriate operators (AND/OR)++6. **Namespace Management**:+ - Use namespaces for multi-tenant isolation+ - Set appropriate access controls+ - Monitor namespace statistics+ - Clean up unused namespaces++7. **Performance**:+ - Use batch operations when possible+ - Choose appropriate index type for use case+ - Normalize vectors for cosine similarity+ - Cache frequently accessed vectors++8. **Error Handling**:+ - Validate vector dimensions+ - Handle missing metadata gracefully+ - Check namespace existence before operations+ - Handle adapter connection failures++9. **Configuration**:+ - Use environment variables for deployment+ - Use config files for development+ - Set appropriate defaults+ - Document configuration options++10. **Testing**:+ - Test with sample data first+ - Validate search results+ - Test metadata filtering+ - Test namespace isolation+ - Monitor performance metrics+