zeusdb-vector-database 0.2.1__tar.gz → 0.4.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,11 +1,12 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: zeusdb-vector-database
3
- Version: 0.2.1
3
+ Version: 0.4.0
4
4
  Classifier: Programming Language :: Rust
5
5
  Classifier: Programming Language :: Python :: Implementation :: CPython
6
6
  Requires-Dist: numpy>=2.2.6,<3.0.0
7
- Requires-Dist: maturin>=1.9.1 ; extra == 'dev'
7
+ Requires-Dist: maturin>=1.9.3 ; extra == 'dev'
8
8
  Requires-Dist: pytest>=8.4.0 ; extra == 'dev'
9
+ Requires-Dist: psutil>=7.0.0 ; extra == 'dev'
9
10
  Provides-Extra: dev
10
11
  License-File: LICENSE
11
12
  License-File: NOTICE
@@ -15,6 +16,7 @@ License-Expression: Apache-2.0
15
16
  Requires-Python: >=3.10
16
17
  Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
17
18
  Project-URL: Repository, https://github.com/zeusdb/zeusdb-vector-database
19
+ Project-URL: Documentation, https://docs.zeusdb.com/en/latest/vector_database/
18
20
  Project-URL: Bug Tracker, https://github.com/zeusdb/zeusdb-vector-database/issues
19
21
 
20
22
  <p align="center" width="100%">
@@ -44,7 +46,7 @@ Project-URL: Bug Tracker, https://github.com/zeusdb/zeusdb-vector-database/issue
44
46
 
45
47
  <!-- badges: end -->
46
48
 
47
- <br/>
49
+ <br />
48
50
 
49
51
  ## ℹ️ What is ZeusDB Vector Database?
50
52
 
@@ -755,6 +757,229 @@ Quantization is ideal for production deployments with large vector datasets (100
755
757
 
756
758
  <br/>
757
759
 
760
+ ## 💾 Persistence
761
+
762
+ ZeusDB Vector Database provides production-ready persistence capabilities that allow you to save and restore your vector indexes to disk. This enables you to preserve your work, share indexes between systems, and implement backup strategies for production deployments.
763
+
764
+ The persistence system supports:
765
+
766
+ ✅ **Complete state preservation** – vectors, metadata, HNSW graph structure, and quantization models
767
+ ✅ **Hybrid storage format** – efficient binary encoding for vectors with human-readable JSON for metadata
768
+ ✅ **Quantization support** – seamlessly handles both raw and quantized storage modes
769
+ ✅ **Training state recovery** – preserves PQ training progress and model parameters
770
+ ✅ **Cross-platform compatibility** – indexes saved on one system can be loaded on another
771
+
772
+ <br/>
773
+
774
+ ### 💾 Saving an Index - .save()
775
+
776
+ Use the `.save()` method to persist your index to a `.zdb` directory structure:
777
+
778
+ ```python
779
+ # Import the vector database module
780
+ from zeusdb_vector_database import VectorDatabase
781
+ import numpy as np
782
+
783
+ # Create and populate an index
784
+ vdb = VectorDatabase()
785
+ index = vdb.create("hnsw", dim=1536, space="cosine")
786
+
787
+ # Add some vectors
788
+ vectors = np.random.random((1000, 1536)).astype(np.float32)
789
+ data = {
790
+ 'vectors': vectors.tolist(),
791
+ 'ids': [f'doc_{i}' for i in range(1000)],
792
+ 'metadatas': [{'category': f'cat_{i%5}', 'index': i} for i in range(1000)]
793
+ }
794
+ index.add(data)
795
+
796
+ # Save the complete index to disk
797
+ index.save("my_index.zdb")
798
+ ```
799
+
800
+ <br />
801
+
802
+ ### 📂 Loading an Index - .load()
803
+
804
+ Use the .load() method to restore a previously saved index:
805
+
806
+ ```python
807
+ # Load the index from disk
808
+ vdb = VectorDatabase()
809
+ loaded_index = vdb.load("my_index.zdb")
810
+
811
+ # Verify the index loaded correctly
812
+ print(f"Loaded index with {loaded_index.get_vector_count()} vectors")
813
+ print(f"Index configuration: {loaded_index.info()}")
814
+
815
+ # Test search on loaded index
816
+ query_vector = np.random.random(1536).tolist()
817
+ results = loaded_index.search(query_vector, top_k=3)
818
+ print(f"Search returned {len(results)} results")
819
+ print(results)
820
+ ```
821
+
822
+ <br />
823
+
824
+ ### 🗜️ Persistence with Product Quantization
825
+
826
+ Persistence seamlessly handles quantized indexes, preserving both the compression model and training state:
827
+
828
+ ```python
829
+ # Create index with quantization
830
+ quantization_config = {
831
+ 'type': 'pq',
832
+ 'subvectors': 8,
833
+ 'bits': 8,
834
+ 'training_size': 1000,
835
+ 'storage_mode': 'quantized_only'
836
+ }
837
+
838
+ vdb = VectorDatabase()
839
+ index = vdb.create("hnsw", dim=1536, quantization_config=quantization_config)
840
+
841
+ # Add enough vectors to trigger PQ training
842
+ vectors = np.random.random((2000, 1536)).astype(np.float32)
843
+ data = {
844
+ 'vectors': vectors.tolist(),
845
+ 'ids': [f'vec_{i}' for i in range(2000)]
846
+ }
847
+
848
+ add_result = index.add(data)
849
+ print(f"Added {add_result.total_inserted} vectors")
850
+ print(f"Training progress: {index.get_training_progress():.1f}%")
851
+ print(f"Quantization active: {index.is_quantized()}")
852
+
853
+ # Save quantized index
854
+ index.save("quantized_index.zdb")
855
+
856
+ # Load and verify quantization state is preserved
857
+ loaded_index = vdb.load("quantized_index.zdb")
858
+ print(f"Loaded quantization state: {loaded_index.is_quantized()}")
859
+ print(f"Compression info: {loaded_index.get_quantization_info()}")
860
+ ```
861
+
862
+ <br/>
863
+
864
+ ### 📁 Index Directory Structure
865
+ The .save() method creates a structured directory containing all index components:
866
+
867
+ ```
868
+ my_index.zdb/
869
+ ├── manifest.json # Index metadata and file inventory
870
+ ├── config.json # HNSW configuration parameters
871
+ ├── mappings.bin # ID mappings (binary format)
872
+ ├── metadata.json # Vector metadata (JSON format)
873
+ ├── vectors.bin # Raw vectors (if applicable)
874
+ ├── quantization.json # PQ configuration (if enabled)
875
+ ├── pq_centroids.bin # Trained centroids (if PQ trained)
876
+ ├── pq_codes.bin # Quantized codes (if PQ active)
877
+ └── hnsw_index.hnsw.graph # HNSW graph structure
878
+ ```
879
+
880
+ <br/>
881
+
882
+ ### 🔄 Complete Save/Load Workflow
883
+ Here's a comprehensive example showing the full persistence lifecycle:
884
+
885
+ ```python
886
+ from zeusdb_vector_database import VectorDatabase
887
+ import numpy as np
888
+
889
+ # === PHASE 1: CREATE AND POPULATE INDEX ===
890
+ vdb = VectorDatabase()
891
+ original_index = vdb.create("hnsw", dim=1536, space="cosine", m=16)
892
+
893
+ # Add vectors with rich metadata
894
+ np.random.seed(42) # For reproducible results
895
+ vectors = np.random.random((500, 1536)).astype(np.float32)
896
+
897
+ data = {
898
+ 'vectors': vectors.tolist(),
899
+ 'ids': [f'doc_{i:03d}' for i in range(500)],
900
+ 'metadatas': [
901
+ {
902
+ 'category': ['science', 'tech', 'health', 'finance'][i % 4],
903
+ 'priority': i % 10,
904
+ 'published': i % 2 == 0,
905
+ 'tags': ['important', 'featured'] if i % 5 == 0 else ['standard']
906
+ }
907
+ for i in range(500)
908
+ ]
909
+ }
910
+
911
+ # Populate the index
912
+ add_result = original_index.add(data)
913
+ print(f"✅ Added {add_result.total_inserted} vectors")
914
+
915
+ # Add some index-level metadata
916
+ original_index.add_metadata({
917
+ "dataset": "demo_collection",
918
+ "created_by": "data_team",
919
+ "version": "1.0"
920
+ })
921
+
922
+ # Test search before saving
923
+ query_vector = vectors[0].tolist() # Use first vector as query
924
+ original_results = original_index.search(query_vector, top_k=3)
925
+ print(f"🔍 Original search found {len(original_results)} results")
926
+
927
+ # === PHASE 2: SAVE INDEX ===
928
+ save_path = "demo_index.zdb"
929
+ original_index.save(save_path)
930
+ print(f"💾 Index saved to {save_path}")
931
+
932
+ # === PHASE 3: LOAD INDEX ===
933
+ loaded_index = vdb.load(save_path)
934
+ print(f"📂 Index loaded from {save_path}")
935
+
936
+ # === PHASE 4: VERIFY INTEGRITY ===
937
+ # Check vector count
938
+ assert loaded_index.get_vector_count() == original_index.get_vector_count()
939
+ print(f"✅ Vector count verified: {loaded_index.get_vector_count()}")
940
+
941
+ # Check configuration
942
+ assert loaded_index.info() == original_index.info()
943
+ print(f"✅ Configuration verified: {loaded_index.info()}")
944
+
945
+ # Check metadata preservation
946
+ original_meta = original_index.get_all_metadata()
947
+ loaded_meta = loaded_index.get_all_metadata()
948
+ #assert original_meta == loaded_meta
949
+ print(f"Original meta fields: {len(original_meta)}, Loaded meta fields: {len(loaded_meta)}")
950
+ print(f"✅ Index metadata verified: {len(loaded_meta)} fields")
951
+
952
+ # Test search consistency
953
+ loaded_results = loaded_index.search(query_vector, top_k=3)
954
+ assert len(loaded_results) == len(original_results)
955
+ assert loaded_results[0]['id'] == original_results[0]['id']
956
+ print("✅ Search consistency verified")
957
+
958
+ # Test filtering on loaded index
959
+ filtered_results = loaded_index.search(
960
+ query_vector,
961
+ filter={'category': 'science', 'published': True},
962
+ top_k=5
963
+ )
964
+ print(f"🔍 Filtered search found {len(filtered_results)} results")
965
+
966
+ print("\n🎉 Complete persistence workflow successful!")
967
+ ```
968
+
969
+ ### ⚠️ Important Notes on Persistence
970
+ - Directory Structure: The .save() method creates a directory, not a single file. Ensure you have write permissions for the target location.
971
+
972
+ - Cross-Platform: Saved indexes are portable between different operating systems and Python environments.
973
+
974
+ - Version Compatibility: Indexes include format version information for future compatibility checking.
975
+
976
+ - Memory Efficiency: The persistence format is optimized for both storage size and loading speed.
977
+
978
+ - Atomic Operations: Save operations are designed to be atomic - either the entire index saves successfully or the operation fails without partial corruption.
979
+
980
+
981
+ <br />
982
+
758
983
  ## 🏷️ Metadata Filtering
759
984
 
760
985
  ZeusDB supports rich metadata with full type fidelity. This means your metadata preserves the original Python data types (integers stay integers, floats stay floats, etc.) and enables powerful filtering capabilities.
@@ -833,6 +1058,228 @@ results = index.search(vector=query_embedding, filter=filter, top_k=5)
833
1058
  ```
834
1059
 
835
1060
 
1061
+ <br />
1062
+
1063
+ ## 📝 Logging
1064
+
1065
+ ZeusDB Vector Database includes enterprise-grade structured logging that works automatically out of the box while providing extensive customization for advanced users.
1066
+
1067
+ ### 🚀 Basic Usage - it just works!
1068
+
1069
+ **For most users, logging works automatically with sensible defaults:**
1070
+
1071
+ ```python
1072
+ from zeusdb_vector_database import VectorDatabase
1073
+ # Logging is automatically configured - no setup required!
1074
+
1075
+ vdb = VectorDatabase()
1076
+ index = vdb.create("hnsw", dim=1536)
1077
+
1078
+ # Operations are automatically logged with structured data
1079
+ result = index.add({"vectors": vectors, "ids": ids})
1080
+ results = index.search(query_vector, top_k=5)
1081
+ ```
1082
+
1083
+ **What you get automatically:**
1084
+ - ✅ **Silent by default** - Only errors and warnings in production
1085
+ - ✅ **Environment detection** - Appropriate defaults for dev/prod/testing
1086
+ - ✅ **Structured JSON logs** in production environments
1087
+ - ✅ **Human-readable logs** in development environments
1088
+ - ✅ **Performance timing** on all operations
1089
+ - ✅ **Cross-platform compatibility**
1090
+
1091
+ ### ⚙️ Intermediate Usage (Environment Variables)
1092
+
1093
+ **Control logging behavior with environment variables:**
1094
+
1095
+ #### Quick Development Debugging
1096
+ ```bash
1097
+ export ZEUSDB_LOG_LEVEL=debug
1098
+ python your_app.py
1099
+ ```
1100
+
1101
+ #### Production JSON Logging
1102
+ ```bash
1103
+ export ZEUSDB_LOG_LEVEL=error
1104
+ export ZEUSDB_LOG_FORMAT=json
1105
+ export ZEUSDB_LOG_TARGET=file
1106
+ export ZEUSDB_LOG_FILE=/var/log/zeusdb/app.log
1107
+ python your_app.py
1108
+ ```
1109
+
1110
+ #### Environment Variables Reference
1111
+
1112
+ | Variable | Options | Default | Description |
1113
+ |----------|---------|---------|-------------|
1114
+ | `ZEUSDB_LOG_LEVEL` | `trace`, `debug`, `info`, `warning`, `error`, `critical` | `warning` (dev), `error` (prod) | Controls log verbosity |
1115
+ | `ZEUSDB_LOG_FORMAT` | `human`, `json` | `human` (dev), `json` (prod) | Output format |
1116
+ | `ZEUSDB_LOG_TARGET` | `stdout`, `stderr`, `file` | `stderr` | Where logs go |
1117
+ | `ZEUSDB_LOG_FILE` | `/path/to/file.log` | `zeusdb.log` | Log file path (if target=file) |
1118
+ | `ZEUSDB_LOG_CONSOLE` | `true`, `false` | Auto-detected | Force console output |
1119
+
1120
+ #### Smart Environment Detection
1121
+ The system automatically detects your environment and applies appropriate defaults:
1122
+
1123
+ - **🏭 Production** (`ENVIRONMENT=production`): ERROR level, JSON format, often file output
1124
+ - **💻 Development** (`ENVIRONMENT=development`): WARNING level, human format, console output
1125
+ - **🧪 Testing** (`pytest`, `PYTEST_CURRENT_TEST`): CRITICAL level, minimal output
1126
+ - **📓 Jupyter** (`JUPYTER_SERVER_ROOT`): INFO level, human format, clean output
1127
+ - **🔄 CI/CD** (`CI`, `GITHUB_ACTIONS`): WARNING level, human format for readability
1128
+
1129
+ ### 🔧 Advanced Usage (Programmatic Control)
1130
+
1131
+ **For enterprise environments with existing logging infrastructure:**
1132
+
1133
+ #### Option 1: Disable Auto-Configuration
1134
+ ```python
1135
+ import os
1136
+ os.environ["ZEUSDB_DISABLE_AUTO_LOGGING"] = "1"
1137
+
1138
+ # Now configure your own logging before importing ZeusDB
1139
+ import logging
1140
+ logging.basicConfig(level=logging.INFO, format='%(message)s')
1141
+
1142
+ from zeusdb_vector_database import VectorDatabase # Will respect your existing logging setup
1143
+ ```
1144
+
1145
+ #### Option 2: Programmatic Initialization
1146
+ ```python
1147
+ import os
1148
+ os.environ["ZEUSDB_DISABLE_AUTO_LOGGING"] = "1"
1149
+
1150
+ import zeusdb_vector_database
1151
+
1152
+ # Initialize with JSON to console
1153
+ success = zeusdb_vector_database.init_logging(level="info")
1154
+
1155
+ # OR initialize with file logging
1156
+ success = zeusdb_vector_database.init_file_logging(
1157
+ log_dir="/var/log/myapp",
1158
+ level="debug",
1159
+ file_prefix="zeusdb"
1160
+ )
1161
+
1162
+ # Then use normally
1163
+ vdb = zeusdb_vector_database.VectorDatabase()
1164
+ ```
1165
+
1166
+ #### Option 3: Custom Logger Integration
1167
+ ```python
1168
+ import logging
1169
+ import os
1170
+
1171
+ # Disable auto-configuration
1172
+ os.environ["ZEUSDB_DISABLE_AUTO_LOGGING"] = "1"
1173
+
1174
+ # Set up your own logger first
1175
+ logger = logging.getLogger("myapp.zeusdb")
1176
+ logger.setLevel(logging.INFO)
1177
+
1178
+ # Configure Rust logging to match
1179
+ os.environ["ZEUSDB_LOG_LEVEL"] = "info"
1180
+ os.environ["ZEUSDB_LOG_FORMAT"] = "json"
1181
+
1182
+ from zeusdb_vector_database import VectorDatabase
1183
+ # ZeusDB will integrate with your logging setup
1184
+ ```
1185
+
1186
+ ### 📊 Log Output Examples
1187
+
1188
+ #### Human-Readable (Development)
1189
+ ```
1190
+ 2025-01-15 10:30:15 - zeusdb.vector - INFO - Index created: dim=1536, vectors=0
1191
+ 2025-01-15 10:30:16 - zeusdb.vector - INFO - Added 1000 vectors in 45ms
1192
+ 2025-01-15 10:30:16 - zeusdb.vector - DEBUG - Search completed: 5 results in 2ms
1193
+ ```
1194
+
1195
+ #### Structured JSON (Production)
1196
+ ```json
1197
+ {"timestamp":"2025-01-15T10:30:15.123Z","level":"INFO","operation":"index_creation","dim":1536,"space":"cosine","duration_ms":12}
1198
+ {"timestamp":"2025-01-15T10:30:16.456Z","level":"INFO","operation":"vector_addition","total_inserted":1000,"duration_ms":45}
1199
+ {"timestamp":"2025-01-15T10:30:16.789Z","level":"DEBUG","operation":"search_complete","results_count":5,"duration_ms":2}
1200
+ ```
1201
+
1202
+ ### 🔍 Monitoring and Observability
1203
+
1204
+ #### Key Metrics to Monitor
1205
+ - **`operation`**: Type of operation (index_creation, vector_addition, search, etc.)
1206
+ - **`duration_ms`**: Performance timing for all operations
1207
+ - **`total_inserted`**, **`total_errors`**: Success/failure rates
1208
+ - **`compression_ratio`**: Memory efficiency with quantization
1209
+ - **`training_progress`**: Quantization training status
1210
+
1211
+ #### Production Alerting Examples
1212
+ ```bash
1213
+ # Monitor error rates
1214
+ grep '"level":"ERROR"' /var/log/zeusdb/app.log | wc -l
1215
+
1216
+ # Track performance degradation
1217
+ grep '"operation":"search"' /var/log/zeusdb/app.log | jq '.duration_ms' | avg
1218
+
1219
+ # Watch quantization training
1220
+ grep '"operation":"pq_training"' /var/log/zeusdb/app.log | tail -f
1221
+ ```
1222
+
1223
+ ### 🛠️ Troubleshooting
1224
+
1225
+ #### Common Issues
1226
+
1227
+ **Logs not appearing?**
1228
+ ```bash
1229
+ # Check if auto-logging is disabled
1230
+ echo $ZEUSDB_DISABLE_AUTO_LOGGING
1231
+
1232
+ # Verify log level
1233
+ ZEUSDB_LOG_LEVEL=debug python -c "import zeusdb; print('Logging active')"
1234
+ ```
1235
+
1236
+ **File logging not working?**
1237
+ ```bash
1238
+ # Check permissions
1239
+ ls -la /path/to/log/directory
1240
+
1241
+ # Test with console first
1242
+ ZEUSDB_LOG_TARGET=stderr ZEUSDB_LOG_LEVEL=info python your_app.py
1243
+ ```
1244
+
1245
+ **Want to see Rust logs specifically?**
1246
+ ```bash
1247
+ # Enable trace level to see all Rust operations
1248
+ ZEUSDB_LOG_LEVEL=trace python your_app.py
1249
+ ```
1250
+
1251
+ #### Performance Impact
1252
+ - **Minimal overhead**: Structured logging adds <1% performance impact
1253
+ - **Async file writing**: File logging doesn't block operations
1254
+ - **Smart buffering**: Logs are efficiently batched for performance
1255
+
1256
+ ### 🎯 Best Practices
1257
+
1258
+ #### Development
1259
+ ```bash
1260
+ export ZEUSDB_LOG_LEVEL=debug
1261
+ export ZEUSDB_LOG_FORMAT=human
1262
+ ```
1263
+
1264
+ #### Staging
1265
+ ```bash
1266
+ export ZEUSDB_LOG_LEVEL=info
1267
+ export ZEUSDB_LOG_FORMAT=json
1268
+ export ZEUSDB_LOG_TARGET=file
1269
+ export ZEUSDB_LOG_FILE=logs/zeusdb-staging.log
1270
+ ```
1271
+
1272
+ #### Production
1273
+ ```bash
1274
+ export ENVIRONMENT=production
1275
+ export ZEUSDB_LOG_LEVEL=error
1276
+ export ZEUSDB_LOG_FORMAT=json
1277
+ export ZEUSDB_LOG_TARGET=file
1278
+ export ZEUSDB_LOG_FILE=/var/log/zeusdb/production.log
1279
+ ```
1280
+
1281
+ The logging system is designed to be **invisible when you don't need it** and **powerful when you do**. Most users will never need to configure anything, while enterprise users get full control over observability.
1282
+
836
1283
  <br/>
837
1284
 
838
1285
  ## 📄 License