zeusdb-vector-database 0.1.1__tar.gz → 0.1.2__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.
- {zeusdb_vector_database-0.1.1 → zeusdb_vector_database-0.1.2}/PKG-INFO +67 -12
- {zeusdb_vector_database-0.1.1 → zeusdb_vector_database-0.1.2}/README.md +66 -11
- {zeusdb_vector_database-0.1.1 → zeusdb_vector_database-0.1.2}/pyproject.toml +1 -1
- {zeusdb_vector_database-0.1.1 → zeusdb_vector_database-0.1.2}/src/zeusdb_vector_database/__init__.py +1 -1
- {zeusdb_vector_database-0.1.1 → zeusdb_vector_database-0.1.2}/vdb-core/Cargo.lock +1 -1
- {zeusdb_vector_database-0.1.1 → zeusdb_vector_database-0.1.2}/vdb-core/Cargo.toml +1 -1
- {zeusdb_vector_database-0.1.1 → zeusdb_vector_database-0.1.2}/vdb-core/src/hnsw_index.rs +391 -80
- {zeusdb_vector_database-0.1.1 → zeusdb_vector_database-0.1.2}/LICENSE +0 -0
- {zeusdb_vector_database-0.1.1 → zeusdb_vector_database-0.1.2}/NOTICE +0 -0
- {zeusdb_vector_database-0.1.1 → zeusdb_vector_database-0.1.2}/src/zeusdb_vector_database/py.typed +0 -0
- {zeusdb_vector_database-0.1.1 → zeusdb_vector_database-0.1.2}/src/zeusdb_vector_database/vector_database.py +0 -0
- {zeusdb_vector_database-0.1.1 → zeusdb_vector_database-0.1.2}/vdb-core/src/lib.rs +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: zeusdb-vector-database
|
|
3
|
-
Version: 0.1.
|
|
3
|
+
Version: 0.1.2
|
|
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
|
|
@@ -207,7 +207,9 @@ index = vdb.create(
|
|
|
207
207
|
)
|
|
208
208
|
```
|
|
209
209
|
|
|
210
|
-
|
|
210
|
+
<br/>
|
|
211
|
+
|
|
212
|
+
#### 📘 Parameters - `create()`
|
|
211
213
|
|
|
212
214
|
| Parameter | Type | Default | Description |
|
|
213
215
|
|------------------|--------|-----------|-----------------------------------------------------------------------------|
|
|
@@ -296,7 +298,9 @@ print(add_result) # AddResult(inserted=2, errors=0, shape=(2, 2))
|
|
|
296
298
|
|
|
297
299
|
Each format is parsed and validated automatically. Invalid records are skipped, and detailed error messages are returned to help with debugging and retry workflows.
|
|
298
300
|
|
|
299
|
-
|
|
301
|
+
<br/>
|
|
302
|
+
|
|
303
|
+
#### 📘 Parameters - `add()`
|
|
300
304
|
|
|
301
305
|
The `add()` method inserts one or more vectors into the index. Multiple data formats are supported to accommodate different workflows, including native Python types and NumPy arrays.
|
|
302
306
|
|
|
@@ -319,10 +323,9 @@ Helpful for validation, logging, and debugging.
|
|
|
319
323
|
|
|
320
324
|
Query the index using a new vector and retrieve the top-k nearest neighbors. You can also filter by metadata or return the original stored vectors.
|
|
321
325
|
|
|
322
|
-
#### 🔍 Basic
|
|
326
|
+
#### 🔍 Search Example 1 - Basic (Returning Top 2 most similar)
|
|
323
327
|
|
|
324
328
|
```python
|
|
325
|
-
print("\n--- Query returning two most similar results ---")
|
|
326
329
|
results = index.search(vector=query_vector, top_k=2)
|
|
327
330
|
print(results)
|
|
328
331
|
```
|
|
@@ -335,12 +338,12 @@ print(results)
|
|
|
335
338
|
]
|
|
336
339
|
```
|
|
337
340
|
|
|
338
|
-
#### 🔍 Query with metadata filter
|
|
341
|
+
#### 🔍 Search Example 2 - Query with metadata filter
|
|
339
342
|
|
|
340
343
|
This filters on the given metadata after conducting the similarity search.
|
|
341
344
|
|
|
342
345
|
```python
|
|
343
|
-
|
|
346
|
+
query_vector = [0.1, 0.2, 0.3, 0.1, 0.4, 0.2, 0.6, 0.7]
|
|
344
347
|
results = index.search(vector=query_vector, filter={"author": "Alice"}, top_k=5)
|
|
345
348
|
print(results)
|
|
346
349
|
```
|
|
@@ -354,12 +357,11 @@ print(results)
|
|
|
354
357
|
]
|
|
355
358
|
```
|
|
356
359
|
|
|
357
|
-
#### 🔍
|
|
360
|
+
#### 🔍 Search Example 3 - Search results include vectors
|
|
358
361
|
|
|
359
362
|
You can optionally return the stored embedding vectors alongside metadata and similarity scores by setting `return_vector=True`. This is useful when you need access to the raw vectors for downstream tasks such as re-ranking, inspection, or hybrid scoring.
|
|
360
363
|
|
|
361
364
|
```python
|
|
362
|
-
print("\n--- Querying with filter and returning embedding vectors ---")
|
|
363
365
|
results = index.search(vector=query_vector, filter={"split": "test"}, top_k=2, return_vector=True)
|
|
364
366
|
print(results)
|
|
365
367
|
```
|
|
@@ -372,13 +374,66 @@ print(results)
|
|
|
372
374
|
]
|
|
373
375
|
```
|
|
374
376
|
|
|
375
|
-
####
|
|
377
|
+
#### 🔍 Search Example 4 - Batch Search with a list of vectors
|
|
378
|
+
|
|
379
|
+
Perform a similarity search on multiple query vectors simultaneously, returning results for each query.
|
|
380
|
+
|
|
381
|
+
```python
|
|
382
|
+
query_vector =
|
|
383
|
+
[
|
|
384
|
+
[0.1, 0.2, 0.3],
|
|
385
|
+
[0.4, 0.5, 0.6]
|
|
386
|
+
]
|
|
387
|
+
results = index.search(vector=query_vector, top_k=3)
|
|
388
|
+
print(results)
|
|
389
|
+
```
|
|
390
|
+
|
|
391
|
+
*Output*
|
|
392
|
+
```
|
|
393
|
+
[
|
|
394
|
+
[{'id': 'a', 'score': 4.999447078546382e-09, 'metadata': {'category': 'A'}}, {'id': 'b', 'score': 0.02536815218627453, 'metadata': {'category': 'B'}}, {'id': 'c', 'score': 0.04058804363012314, 'metadata': {'category': 'A'}}],
|
|
395
|
+
[{'id': 'b', 'score': 4.591760305316939e-09, 'metadata': {'category': 'B'}}, {'id': 'c', 'score': 0.0018091063247993588, 'metadata': {'category': 'A'}}, {'id': 'a', 'score': 0.025368161499500275, 'metadata': {'category': 'A'}}]
|
|
396
|
+
]
|
|
397
|
+
```
|
|
398
|
+
|
|
399
|
+
#### 🔍 Search Example 5 - Batch Search with NumPy Array
|
|
400
|
+
|
|
401
|
+
Perform a similarity search on multiple query vectors from a NumPy array, returning results for each query.
|
|
402
|
+
|
|
403
|
+
```python
|
|
404
|
+
query_vector = np.array(
|
|
405
|
+
[
|
|
406
|
+
[0.1, 0.2, 0.3],
|
|
407
|
+
[0.7, 0.8, 0.9]
|
|
408
|
+
], dtype=np.float32)
|
|
409
|
+
|
|
410
|
+
results = index.search(vector=query_vector, top_k=3)
|
|
411
|
+
print(results)
|
|
412
|
+
```
|
|
413
|
+
|
|
414
|
+
#### 🔍 Search Example 6 - Batch Search with with metadata filter
|
|
415
|
+
|
|
416
|
+
Performs similarity search on multiple query vectors with metadata filtering, returning filtered results for each query.
|
|
417
|
+
|
|
418
|
+
```python
|
|
419
|
+
results = index.search(
|
|
420
|
+
[[0.1, 0.2, 0.3], [0.7, 0.8, 0.9]],
|
|
421
|
+
filter={"category": "A"},
|
|
422
|
+
top_k=3
|
|
423
|
+
)
|
|
424
|
+
print(results)
|
|
425
|
+
```
|
|
426
|
+
|
|
427
|
+
|
|
428
|
+
<br/>
|
|
429
|
+
|
|
430
|
+
#### 📘 Parameters - `search()`
|
|
376
431
|
|
|
377
|
-
The `
|
|
432
|
+
The `search()` method retrieves the top-k most similar vectors from the index given an input query vector. Results include the vector ID, similarity score, metadata, and (optionally) the stored vector itself.
|
|
378
433
|
|
|
379
434
|
| Parameter | Type | Default | Description |
|
|
380
435
|
|------------------|----------------------------------|-----------|-----------------------------------------------------------------------------|
|
|
381
|
-
| `vector` | `List[float]` or `np.ndarray`
|
|
436
|
+
| `vector` | `List[float]` or `List[List[float]]` or `np.ndarray` | *required* | The query vector (single: `List[float]`) or batch of query vectors (`List[List[float]]` or 2D `np.ndarray`) to compare against the index. Must match the index dimension. |
|
|
382
437
|
| `filter` | `Dict[str, str] \| None` | `None` | Optional metadata filter. Only vectors with matching key-value metadata pairs will be considered in the search. |
|
|
383
438
|
| `top_k` | `int` | `10` | Number of nearest neighbors to return. |
|
|
384
439
|
| `ef_search` | `int \| None` | `max(2 × top_k, 100)` | Search complexity parameter. Higher values improve accuracy at the cost of speed. |
|
|
@@ -188,7 +188,9 @@ index = vdb.create(
|
|
|
188
188
|
)
|
|
189
189
|
```
|
|
190
190
|
|
|
191
|
-
|
|
191
|
+
<br/>
|
|
192
|
+
|
|
193
|
+
#### 📘 Parameters - `create()`
|
|
192
194
|
|
|
193
195
|
| Parameter | Type | Default | Description |
|
|
194
196
|
|------------------|--------|-----------|-----------------------------------------------------------------------------|
|
|
@@ -277,7 +279,9 @@ print(add_result) # AddResult(inserted=2, errors=0, shape=(2, 2))
|
|
|
277
279
|
|
|
278
280
|
Each format is parsed and validated automatically. Invalid records are skipped, and detailed error messages are returned to help with debugging and retry workflows.
|
|
279
281
|
|
|
280
|
-
|
|
282
|
+
<br/>
|
|
283
|
+
|
|
284
|
+
#### 📘 Parameters - `add()`
|
|
281
285
|
|
|
282
286
|
The `add()` method inserts one or more vectors into the index. Multiple data formats are supported to accommodate different workflows, including native Python types and NumPy arrays.
|
|
283
287
|
|
|
@@ -300,10 +304,9 @@ Helpful for validation, logging, and debugging.
|
|
|
300
304
|
|
|
301
305
|
Query the index using a new vector and retrieve the top-k nearest neighbors. You can also filter by metadata or return the original stored vectors.
|
|
302
306
|
|
|
303
|
-
#### 🔍 Basic
|
|
307
|
+
#### 🔍 Search Example 1 - Basic (Returning Top 2 most similar)
|
|
304
308
|
|
|
305
309
|
```python
|
|
306
|
-
print("\n--- Query returning two most similar results ---")
|
|
307
310
|
results = index.search(vector=query_vector, top_k=2)
|
|
308
311
|
print(results)
|
|
309
312
|
```
|
|
@@ -316,12 +319,12 @@ print(results)
|
|
|
316
319
|
]
|
|
317
320
|
```
|
|
318
321
|
|
|
319
|
-
#### 🔍 Query with metadata filter
|
|
322
|
+
#### 🔍 Search Example 2 - Query with metadata filter
|
|
320
323
|
|
|
321
324
|
This filters on the given metadata after conducting the similarity search.
|
|
322
325
|
|
|
323
326
|
```python
|
|
324
|
-
|
|
327
|
+
query_vector = [0.1, 0.2, 0.3, 0.1, 0.4, 0.2, 0.6, 0.7]
|
|
325
328
|
results = index.search(vector=query_vector, filter={"author": "Alice"}, top_k=5)
|
|
326
329
|
print(results)
|
|
327
330
|
```
|
|
@@ -335,12 +338,11 @@ print(results)
|
|
|
335
338
|
]
|
|
336
339
|
```
|
|
337
340
|
|
|
338
|
-
#### 🔍
|
|
341
|
+
#### 🔍 Search Example 3 - Search results include vectors
|
|
339
342
|
|
|
340
343
|
You can optionally return the stored embedding vectors alongside metadata and similarity scores by setting `return_vector=True`. This is useful when you need access to the raw vectors for downstream tasks such as re-ranking, inspection, or hybrid scoring.
|
|
341
344
|
|
|
342
345
|
```python
|
|
343
|
-
print("\n--- Querying with filter and returning embedding vectors ---")
|
|
344
346
|
results = index.search(vector=query_vector, filter={"split": "test"}, top_k=2, return_vector=True)
|
|
345
347
|
print(results)
|
|
346
348
|
```
|
|
@@ -353,13 +355,66 @@ print(results)
|
|
|
353
355
|
]
|
|
354
356
|
```
|
|
355
357
|
|
|
356
|
-
####
|
|
358
|
+
#### 🔍 Search Example 4 - Batch Search with a list of vectors
|
|
359
|
+
|
|
360
|
+
Perform a similarity search on multiple query vectors simultaneously, returning results for each query.
|
|
361
|
+
|
|
362
|
+
```python
|
|
363
|
+
query_vector =
|
|
364
|
+
[
|
|
365
|
+
[0.1, 0.2, 0.3],
|
|
366
|
+
[0.4, 0.5, 0.6]
|
|
367
|
+
]
|
|
368
|
+
results = index.search(vector=query_vector, top_k=3)
|
|
369
|
+
print(results)
|
|
370
|
+
```
|
|
371
|
+
|
|
372
|
+
*Output*
|
|
373
|
+
```
|
|
374
|
+
[
|
|
375
|
+
[{'id': 'a', 'score': 4.999447078546382e-09, 'metadata': {'category': 'A'}}, {'id': 'b', 'score': 0.02536815218627453, 'metadata': {'category': 'B'}}, {'id': 'c', 'score': 0.04058804363012314, 'metadata': {'category': 'A'}}],
|
|
376
|
+
[{'id': 'b', 'score': 4.591760305316939e-09, 'metadata': {'category': 'B'}}, {'id': 'c', 'score': 0.0018091063247993588, 'metadata': {'category': 'A'}}, {'id': 'a', 'score': 0.025368161499500275, 'metadata': {'category': 'A'}}]
|
|
377
|
+
]
|
|
378
|
+
```
|
|
379
|
+
|
|
380
|
+
#### 🔍 Search Example 5 - Batch Search with NumPy Array
|
|
381
|
+
|
|
382
|
+
Perform a similarity search on multiple query vectors from a NumPy array, returning results for each query.
|
|
383
|
+
|
|
384
|
+
```python
|
|
385
|
+
query_vector = np.array(
|
|
386
|
+
[
|
|
387
|
+
[0.1, 0.2, 0.3],
|
|
388
|
+
[0.7, 0.8, 0.9]
|
|
389
|
+
], dtype=np.float32)
|
|
390
|
+
|
|
391
|
+
results = index.search(vector=query_vector, top_k=3)
|
|
392
|
+
print(results)
|
|
393
|
+
```
|
|
394
|
+
|
|
395
|
+
#### 🔍 Search Example 6 - Batch Search with with metadata filter
|
|
396
|
+
|
|
397
|
+
Performs similarity search on multiple query vectors with metadata filtering, returning filtered results for each query.
|
|
398
|
+
|
|
399
|
+
```python
|
|
400
|
+
results = index.search(
|
|
401
|
+
[[0.1, 0.2, 0.3], [0.7, 0.8, 0.9]],
|
|
402
|
+
filter={"category": "A"},
|
|
403
|
+
top_k=3
|
|
404
|
+
)
|
|
405
|
+
print(results)
|
|
406
|
+
```
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
<br/>
|
|
410
|
+
|
|
411
|
+
#### 📘 Parameters - `search()`
|
|
357
412
|
|
|
358
|
-
The `
|
|
413
|
+
The `search()` method retrieves the top-k most similar vectors from the index given an input query vector. Results include the vector ID, similarity score, metadata, and (optionally) the stored vector itself.
|
|
359
414
|
|
|
360
415
|
| Parameter | Type | Default | Description |
|
|
361
416
|
|------------------|----------------------------------|-----------|-----------------------------------------------------------------------------|
|
|
362
|
-
| `vector` | `List[float]` or `np.ndarray`
|
|
417
|
+
| `vector` | `List[float]` or `List[List[float]]` or `np.ndarray` | *required* | The query vector (single: `List[float]`) or batch of query vectors (`List[List[float]]` or 2D `np.ndarray`) to compare against the index. Must match the index dimension. |
|
|
363
418
|
| `filter` | `Dict[str, str] \| None` | `None` | Optional metadata filter. Only vectors with matching key-value metadata pairs will be considered in the search. |
|
|
364
419
|
| `top_k` | `int` | `10` | Number of nearest neighbors to return. |
|
|
365
420
|
| `ef_search` | `int \| None` | `max(2 × top_k, 100)` | Search complexity parameter. Higher values improve accuracy at the cost of speed. |
|
|
@@ -183,99 +183,213 @@ impl HNSWIndex {
|
|
|
183
183
|
}
|
|
184
184
|
}
|
|
185
185
|
|
|
186
|
-
/// GIL-optimized search with HNSW locking
|
|
186
|
+
// /// GIL-optimized search with HNSW locking
|
|
187
|
+
// #[pyo3(signature = (vector, filter=None, top_k=10, ef_search=None, return_vector=false))]
|
|
188
|
+
// pub fn search(
|
|
189
|
+
// &self,
|
|
190
|
+
// py: Python<'_>,
|
|
191
|
+
// vector: Vec<f32>,
|
|
192
|
+
// filter: Option<&Bound<PyDict>>,
|
|
193
|
+
// top_k: usize,
|
|
194
|
+
// ef_search: Option<usize>,
|
|
195
|
+
// return_vector: bool,
|
|
196
|
+
// ) -> PyResult<Vec<Py<PyDict>>> {
|
|
197
|
+
// if vector.len() != self.dim {
|
|
198
|
+
// return Err(PyErr::new::<pyo3::exceptions::PyValueError, _>(format!(
|
|
199
|
+
// "Search vector dimension mismatch: expected {}, got {}",
|
|
200
|
+
// self.dim, vector.len()
|
|
201
|
+
// )));
|
|
202
|
+
// }
|
|
203
|
+
|
|
204
|
+
// // Parse filter while still have GIL
|
|
205
|
+
// let filter_conditions = if let Some(filter_dict) = filter {
|
|
206
|
+
// Some(self.python_dict_to_value_map(filter_dict)?)
|
|
207
|
+
// } else {
|
|
208
|
+
// None
|
|
209
|
+
// };
|
|
210
|
+
|
|
211
|
+
// let ef = ef_search.unwrap_or_else(|| std::cmp::max(2 * top_k, 100));
|
|
212
|
+
|
|
213
|
+
// // Release GIL but use locking for HNSW
|
|
214
|
+
// let search_results = py.allow_threads(|| {
|
|
215
|
+
// // Step 1: HNSW search (needs exclusive access, but brief)
|
|
216
|
+
// let hnsw_results = {
|
|
217
|
+
// let hnsw_guard = self.hnsw.lock().unwrap();
|
|
218
|
+
// hnsw_guard.search(&vector, top_k, ef)
|
|
219
|
+
// }; // HNSW lock released here - This is critical for performance!
|
|
220
|
+
|
|
221
|
+
// // Step 2: Data lookup with RwLock (concurrent reads possible)
|
|
222
|
+
// let vectors = self.vectors.read().unwrap();
|
|
223
|
+
// let vector_metadata = self.vector_metadata.read().unwrap();
|
|
224
|
+
// let rev_map = self.rev_map.read().unwrap();
|
|
225
|
+
|
|
226
|
+
// let mut results = Vec::with_capacity(hnsw_results.len());
|
|
227
|
+
|
|
228
|
+
// let has_filter = filter_conditions.is_some();
|
|
229
|
+
|
|
230
|
+
// for neighbor in hnsw_results {
|
|
231
|
+
// let score = neighbor.distance;
|
|
232
|
+
// let internal_id = neighbor.get_origin_id();
|
|
233
|
+
|
|
234
|
+
// if let Some(ext_id) = rev_map.get(&internal_id) {
|
|
235
|
+
// if has_filter {
|
|
236
|
+
// if let Some(meta) = vector_metadata.get(ext_id) {
|
|
237
|
+
// let filter_conds = filter_conditions.as_ref().unwrap(); // Safe unwrap
|
|
238
|
+
// if !self.matches_filter(meta, filter_conds).unwrap_or(false) {
|
|
239
|
+
// continue;
|
|
240
|
+
// }
|
|
241
|
+
// } else {
|
|
242
|
+
// continue;
|
|
243
|
+
// }
|
|
244
|
+
// }
|
|
245
|
+
|
|
246
|
+
// // Collect data for Python object creation
|
|
247
|
+
// let metadata = vector_metadata.get(ext_id).cloned().unwrap_or_default();
|
|
248
|
+
// let vector_data = if return_vector {
|
|
249
|
+
// vectors.get(ext_id).cloned()
|
|
250
|
+
// } else {
|
|
251
|
+
// None
|
|
252
|
+
// };
|
|
253
|
+
|
|
254
|
+
// results.push((ext_id.clone(), score, metadata, vector_data));
|
|
255
|
+
// }
|
|
256
|
+
// }
|
|
257
|
+
|
|
258
|
+
// results
|
|
259
|
+
// }); // GIL is reacquired here
|
|
260
|
+
|
|
261
|
+
// // Step 3: Convert to Python objects (needs GIL)
|
|
262
|
+
// let mut output = Vec::with_capacity(search_results.len());
|
|
263
|
+
// for (id, score, metadata, vector_data) in search_results {
|
|
264
|
+
// let dict = PyDict::new(py);
|
|
265
|
+
// dict.set_item("id", id)?;
|
|
266
|
+
// dict.set_item("score", score)?;
|
|
267
|
+
// dict.set_item("metadata", self.value_map_to_python(&metadata, py)?)?;
|
|
268
|
+
|
|
269
|
+
// if let Some(vec) = vector_data {
|
|
270
|
+
// dict.set_item("vector", vec)?;
|
|
271
|
+
// }
|
|
272
|
+
|
|
273
|
+
// output.push(dict.into());
|
|
274
|
+
// }
|
|
275
|
+
|
|
276
|
+
// Ok(output)
|
|
277
|
+
// }
|
|
278
|
+
|
|
279
|
+
// SEARCH METHOD
|
|
280
|
+
/// Enhanced search method with automatic batch detection and optimization
|
|
187
281
|
#[pyo3(signature = (vector, filter=None, top_k=10, ef_search=None, return_vector=false))]
|
|
188
282
|
pub fn search(
|
|
189
283
|
&self,
|
|
190
284
|
py: Python<'_>,
|
|
191
|
-
vector:
|
|
285
|
+
vector: Bound<PyAny>,
|
|
192
286
|
filter: Option<&Bound<PyDict>>,
|
|
193
287
|
top_k: usize,
|
|
194
288
|
ef_search: Option<usize>,
|
|
195
289
|
return_vector: bool,
|
|
196
|
-
) -> PyResult<
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
290
|
+
) -> PyResult<PyObject> {
|
|
291
|
+
let ef = ef_search.unwrap_or_else(|| std::cmp::max(2 * top_k, 100));
|
|
292
|
+
let filter_conditions = filter.map(|f| self.python_dict_to_value_map(f)).transpose()?;
|
|
293
|
+
|
|
294
|
+
// Detect batch vs single query with comprehensive input support
|
|
295
|
+
if let Ok(list_vec) = vector.extract::<Vec<Vec<f32>>>() {
|
|
296
|
+
// Format: List of vectors [[0.1, 0.2], [0.3, 0.4]]
|
|
297
|
+
let results = self.batch_search_internal(&list_vec, filter_conditions.as_ref(), top_k, ef, return_vector, py)?;
|
|
298
|
+
Ok(PyList::new(py, results)?.into())
|
|
299
|
+
} else if let Ok(np_array) = vector.downcast::<PyArray2<f32>>() {
|
|
300
|
+
// Format: NumPy 2D array (N, dims)
|
|
301
|
+
let readonly = np_array.readonly();
|
|
302
|
+
let shape = readonly.shape();
|
|
203
303
|
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
};
|
|
304
|
+
if shape.len() != 2 || shape[1] != self.dim {
|
|
305
|
+
return Err(PyErr::new::<pyo3::exceptions::PyValueError, _>(format!(
|
|
306
|
+
"NumPy array must have shape (N, {}), got {:?}", self.dim, shape
|
|
307
|
+
)));
|
|
308
|
+
}
|
|
210
309
|
|
|
211
|
-
|
|
310
|
+
let flat = readonly.as_slice()?;
|
|
311
|
+
let batch: Vec<Vec<f32>> = flat.chunks(self.dim).map(|chunk| chunk.to_vec()).collect();
|
|
312
|
+
let results = self.batch_search_internal(&batch, filter_conditions.as_ref(), top_k, ef, return_vector, py)?;
|
|
313
|
+
Ok(PyList::new(py, results)?.into())
|
|
314
|
+
} else {
|
|
315
|
+
// Single vector path - enhanced with NumPy 1D support
|
|
316
|
+
let single_vec = if let Ok(array1d) = vector.downcast::<PyArray1<f32>>() {
|
|
317
|
+
array1d.readonly().as_slice()?.to_vec()
|
|
318
|
+
} else {
|
|
319
|
+
vector.extract::<Vec<f32>>()?
|
|
320
|
+
};
|
|
212
321
|
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
}; // HNSW lock released here - This is critical for performance!
|
|
220
|
-
|
|
221
|
-
// Step 2: Data lookup with RwLock (concurrent reads possible)
|
|
222
|
-
let vectors = self.vectors.read().unwrap();
|
|
223
|
-
let vector_metadata = self.vector_metadata.read().unwrap();
|
|
224
|
-
let rev_map = self.rev_map.read().unwrap();
|
|
225
|
-
|
|
226
|
-
let mut results = Vec::with_capacity(hnsw_results.len());
|
|
322
|
+
if single_vec.len() != self.dim {
|
|
323
|
+
return Err(PyErr::new::<pyo3::exceptions::PyValueError, _>(format!(
|
|
324
|
+
"Search vector dimension mismatch: expected {}, got {}",
|
|
325
|
+
self.dim, single_vec.len()
|
|
326
|
+
)));
|
|
327
|
+
}
|
|
227
328
|
|
|
228
|
-
let
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
329
|
+
let search_results = py.allow_threads(|| {
|
|
330
|
+
let hnsw_results = {
|
|
331
|
+
let hnsw_guard = self.hnsw.lock().unwrap();
|
|
332
|
+
hnsw_guard.search(&single_vec, top_k, ef)
|
|
333
|
+
};
|
|
334
|
+
|
|
335
|
+
let vectors = self.vectors.read().unwrap();
|
|
336
|
+
let vector_metadata = self.vector_metadata.read().unwrap();
|
|
337
|
+
let rev_map = self.rev_map.read().unwrap();
|
|
338
|
+
|
|
339
|
+
let mut results = Vec::with_capacity(hnsw_results.len());
|
|
340
|
+
let has_filter = filter_conditions.is_some();
|
|
341
|
+
|
|
342
|
+
for neighbor in hnsw_results {
|
|
343
|
+
let score = neighbor.distance;
|
|
344
|
+
let internal_id = neighbor.get_origin_id();
|
|
345
|
+
|
|
346
|
+
if let Some(ext_id) = rev_map.get(&internal_id) {
|
|
347
|
+
if has_filter {
|
|
348
|
+
if let Some(meta) = vector_metadata.get(ext_id) {
|
|
349
|
+
let filter_conds = filter_conditions.as_ref().unwrap();
|
|
350
|
+
if !self.matches_filter(meta, filter_conds).unwrap_or(false) {
|
|
351
|
+
continue;
|
|
352
|
+
}
|
|
353
|
+
} else {
|
|
239
354
|
continue;
|
|
240
355
|
}
|
|
241
|
-
} else {
|
|
242
|
-
continue;
|
|
243
356
|
}
|
|
357
|
+
|
|
358
|
+
let metadata = vector_metadata.get(ext_id).cloned().unwrap_or_default();
|
|
359
|
+
let vector_data = if return_vector {
|
|
360
|
+
vectors.get(ext_id).cloned()
|
|
361
|
+
} else {
|
|
362
|
+
None
|
|
363
|
+
};
|
|
364
|
+
|
|
365
|
+
results.push((ext_id.clone(), score, metadata, vector_data));
|
|
244
366
|
}
|
|
245
|
-
|
|
246
|
-
// Collect data for Python object creation
|
|
247
|
-
let metadata = vector_metadata.get(ext_id).cloned().unwrap_or_default();
|
|
248
|
-
let vector_data = if return_vector {
|
|
249
|
-
vectors.get(ext_id).cloned()
|
|
250
|
-
} else {
|
|
251
|
-
None
|
|
252
|
-
};
|
|
253
|
-
|
|
254
|
-
results.push((ext_id.clone(), score, metadata, vector_data));
|
|
255
367
|
}
|
|
368
|
+
|
|
369
|
+
results
|
|
370
|
+
});
|
|
371
|
+
|
|
372
|
+
// let mut output = Vec::with_capacity(search_results.len());
|
|
373
|
+
let mut output: Vec<Py<PyDict>> = Vec::with_capacity(search_results.len());
|
|
374
|
+
for (id, score, metadata, vector_data) in search_results {
|
|
375
|
+
let dict = PyDict::new(py);
|
|
376
|
+
dict.set_item("id", id)?;
|
|
377
|
+
dict.set_item("score", score)?;
|
|
378
|
+
dict.set_item("metadata", self.value_map_to_python(&metadata, py)?)?;
|
|
379
|
+
if let Some(vec) = vector_data {
|
|
380
|
+
dict.set_item("vector", vec)?;
|
|
381
|
+
}
|
|
382
|
+
output.push(dict.into());
|
|
256
383
|
}
|
|
257
|
-
|
|
258
|
-
results
|
|
259
|
-
}); // GIL is reacquired here
|
|
260
|
-
|
|
261
|
-
// Step 3: Convert to Python objects (needs GIL)
|
|
262
|
-
let mut output = Vec::with_capacity(search_results.len());
|
|
263
|
-
for (id, score, metadata, vector_data) in search_results {
|
|
264
|
-
let dict = PyDict::new(py);
|
|
265
|
-
dict.set_item("id", id)?;
|
|
266
|
-
dict.set_item("score", score)?;
|
|
267
|
-
dict.set_item("metadata", self.value_map_to_python(&metadata, py)?)?;
|
|
268
|
-
|
|
269
|
-
if let Some(vec) = vector_data {
|
|
270
|
-
dict.set_item("vector", vec)?;
|
|
271
|
-
}
|
|
272
|
-
|
|
273
|
-
output.push(dict.into());
|
|
274
|
-
}
|
|
275
384
|
|
|
276
|
-
|
|
385
|
+
Ok(PyList::new(py, output)?.into())
|
|
386
|
+
}
|
|
277
387
|
}
|
|
278
388
|
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
|
|
279
393
|
/// Thread-safe get_records implementation
|
|
280
394
|
#[pyo3(signature = (input, return_vector = true))]
|
|
281
395
|
pub fn get_records(&self, py: Python<'_>, input: &Bound<PyAny>, return_vector: bool) -> PyResult<Vec<Py<PyDict>>> {
|
|
@@ -438,15 +552,12 @@ impl HNSWIndex {
|
|
|
438
552
|
.collect();
|
|
439
553
|
|
|
440
554
|
let mut results = HashMap::new();
|
|
441
|
-
|
|
442
|
-
// Sequential benchmark
|
|
555
|
+
|
|
556
|
+
// Sequential benchmark (using raw search for cleaner performance measurement)
|
|
443
557
|
let start = Instant::now();
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
}
|
|
448
|
-
Ok::<(), PyErr>(())
|
|
449
|
-
})?;
|
|
558
|
+
for query in &queries {
|
|
559
|
+
let _ = self.raw_search_no_gil(query);
|
|
560
|
+
}
|
|
450
561
|
let sequential_time = start.elapsed().as_secs_f64();
|
|
451
562
|
results.insert("sequential_time".to_string(), sequential_time);
|
|
452
563
|
results.insert("sequential_qps".to_string(), queries.len() as f64 / sequential_time);
|
|
@@ -1125,4 +1236,204 @@ impl HNSWIndex {
|
|
|
1125
1236
|
|
|
1126
1237
|
Ok(py_obj)
|
|
1127
1238
|
}
|
|
1239
|
+
|
|
1240
|
+
/// Internal batch search method for multiple query vectors (not exposed to Python)
|
|
1241
|
+
/// Automatically chooses optimal strategy based on batch size
|
|
1242
|
+
fn batch_search_internal(
|
|
1243
|
+
&self,
|
|
1244
|
+
vectors: &[Vec<f32>],
|
|
1245
|
+
filter_conditions: Option<&HashMap<String, Value>>,
|
|
1246
|
+
top_k: usize,
|
|
1247
|
+
ef: usize,
|
|
1248
|
+
return_vector: bool,
|
|
1249
|
+
py: Python<'_>,
|
|
1250
|
+
) -> PyResult<Vec<Vec<Py<PyDict>>>> {
|
|
1251
|
+
// Validate all vectors have correct dimension
|
|
1252
|
+
for (i, vector) in vectors.iter().enumerate() {
|
|
1253
|
+
if vector.len() != self.dim {
|
|
1254
|
+
return Err(PyErr::new::<pyo3::exceptions::PyValueError, _>(
|
|
1255
|
+
format!("Vector {}: dimension mismatch: expected {}, got {}",
|
|
1256
|
+
i, self.dim, vector.len())));
|
|
1257
|
+
}
|
|
1258
|
+
}
|
|
1259
|
+
|
|
1260
|
+
// Choose strategy based on batch size
|
|
1261
|
+
if vectors.len() <= 5 {
|
|
1262
|
+
self.batch_search_sequential(vectors, filter_conditions, top_k, ef, return_vector, py)
|
|
1263
|
+
} else {
|
|
1264
|
+
self.batch_search_parallel(vectors, filter_conditions, top_k, ef, return_vector, py)
|
|
1265
|
+
}
|
|
1266
|
+
}
|
|
1267
|
+
|
|
1268
|
+
/// Sequential batch processing (for small batches - single HNSW lock)
|
|
1269
|
+
/// Most efficient for 2-5 queries due to reduced lock overhead
|
|
1270
|
+
fn batch_search_sequential(
|
|
1271
|
+
&self,
|
|
1272
|
+
vectors: &[Vec<f32>],
|
|
1273
|
+
filter_conditions: Option<&HashMap<String, Value>>,
|
|
1274
|
+
top_k: usize,
|
|
1275
|
+
ef: usize,
|
|
1276
|
+
return_vector: bool,
|
|
1277
|
+
py: Python<'_>,
|
|
1278
|
+
) -> PyResult<Vec<Vec<Py<PyDict>>>> {
|
|
1279
|
+
let rust_results = py.allow_threads(|| {
|
|
1280
|
+
// Single HNSW lock for entire batch (most efficient for small batches)
|
|
1281
|
+
let hnsw_guard = self.hnsw.lock().unwrap();
|
|
1282
|
+
let vector_store = self.vectors.read().unwrap();
|
|
1283
|
+
let metadata_store = self.vector_metadata.read().unwrap();
|
|
1284
|
+
let rev_map = self.rev_map.read().unwrap();
|
|
1285
|
+
|
|
1286
|
+
let mut all_results = Vec::with_capacity(vectors.len());
|
|
1287
|
+
|
|
1288
|
+
for vector in vectors {
|
|
1289
|
+
let neighbors = hnsw_guard.search(vector, top_k, ef);
|
|
1290
|
+
let mut query_results = Vec::with_capacity(neighbors.len());
|
|
1291
|
+
|
|
1292
|
+
for neighbor in neighbors {
|
|
1293
|
+
let internal_id = neighbor.get_origin_id();
|
|
1294
|
+
|
|
1295
|
+
if let Some(ext_id) = rev_map.get(&internal_id) {
|
|
1296
|
+
// Apply filter if specified
|
|
1297
|
+
if let Some(filter_conds) = filter_conditions {
|
|
1298
|
+
if let Some(meta) = metadata_store.get(ext_id) {
|
|
1299
|
+
if !self.matches_filter(meta, filter_conds).unwrap_or(false) {
|
|
1300
|
+
continue;
|
|
1301
|
+
}
|
|
1302
|
+
} else {
|
|
1303
|
+
continue;
|
|
1304
|
+
}
|
|
1305
|
+
}
|
|
1306
|
+
|
|
1307
|
+
let metadata = metadata_store.get(ext_id).cloned().unwrap_or_default();
|
|
1308
|
+
let vector_data = if return_vector {
|
|
1309
|
+
vector_store.get(ext_id).cloned()
|
|
1310
|
+
} else {
|
|
1311
|
+
None
|
|
1312
|
+
};
|
|
1313
|
+
|
|
1314
|
+
query_results.push((ext_id.clone(), neighbor.distance, metadata, vector_data));
|
|
1315
|
+
}
|
|
1316
|
+
}
|
|
1317
|
+
|
|
1318
|
+
all_results.push(query_results);
|
|
1319
|
+
}
|
|
1320
|
+
|
|
1321
|
+
all_results
|
|
1322
|
+
});
|
|
1323
|
+
|
|
1324
|
+
// Convert to Python objects (needs GIL)
|
|
1325
|
+
let mut output = Vec::with_capacity(rust_results.len());
|
|
1326
|
+
for batch_result in rust_results {
|
|
1327
|
+
let mut py_batch = Vec::with_capacity(batch_result.len());
|
|
1328
|
+
|
|
1329
|
+
for (id, score, metadata, vector_data) in batch_result {
|
|
1330
|
+
let dict = PyDict::new(py);
|
|
1331
|
+
dict.set_item("id", id)?;
|
|
1332
|
+
dict.set_item("score", score)?;
|
|
1333
|
+
dict.set_item("metadata", self.value_map_to_python(&metadata, py)?)?;
|
|
1334
|
+
|
|
1335
|
+
if let Some(vec) = vector_data {
|
|
1336
|
+
dict.set_item("vector", vec)?;
|
|
1337
|
+
}
|
|
1338
|
+
|
|
1339
|
+
py_batch.push(dict.into());
|
|
1340
|
+
}
|
|
1341
|
+
|
|
1342
|
+
output.push(py_batch);
|
|
1343
|
+
}
|
|
1344
|
+
|
|
1345
|
+
Ok(output)
|
|
1346
|
+
}
|
|
1347
|
+
|
|
1348
|
+
/// Parallel batch processing (for larger batches - brief individual locks)
|
|
1349
|
+
/// Scales with CPU cores for 6+ queries
|
|
1350
|
+
fn batch_search_parallel(
|
|
1351
|
+
&self,
|
|
1352
|
+
vectors: &[Vec<f32>],
|
|
1353
|
+
filter_conditions: Option<&HashMap<String, Value>>,
|
|
1354
|
+
top_k: usize,
|
|
1355
|
+
ef: usize,
|
|
1356
|
+
return_vector: bool,
|
|
1357
|
+
py: Python<'_>,
|
|
1358
|
+
) -> PyResult<Vec<Vec<Py<PyDict>>>> {
|
|
1359
|
+
let rust_results = py.allow_threads(|| {
|
|
1360
|
+
// Parallel processing with brief individual HNSW locks
|
|
1361
|
+
let results: Vec<Vec<(String, f32, HashMap<String, Value>, Option<Vec<f32>>)>> = vectors
|
|
1362
|
+
.par_iter()
|
|
1363
|
+
.map(|vector| {
|
|
1364
|
+
// Brief HNSW search (individual lock per query)
|
|
1365
|
+
let neighbors = {
|
|
1366
|
+
let hnsw_guard = self.hnsw.lock().unwrap();
|
|
1367
|
+
hnsw_guard.search(vector, top_k, ef)
|
|
1368
|
+
}; // Lock released immediately after search
|
|
1369
|
+
|
|
1370
|
+
// Concurrent data lookup (RwLock allows parallel reads)
|
|
1371
|
+
let vector_store = self.vectors.read().unwrap();
|
|
1372
|
+
let metadata_store = self.vector_metadata.read().unwrap();
|
|
1373
|
+
let rev_map = self.rev_map.read().unwrap();
|
|
1374
|
+
|
|
1375
|
+
let mut query_results = Vec::with_capacity(neighbors.len());
|
|
1376
|
+
|
|
1377
|
+
for neighbor in neighbors {
|
|
1378
|
+
let internal_id = neighbor.get_origin_id();
|
|
1379
|
+
|
|
1380
|
+
if let Some(ext_id) = rev_map.get(&internal_id) {
|
|
1381
|
+
// Apply filter if specified
|
|
1382
|
+
if let Some(filter_conds) = filter_conditions {
|
|
1383
|
+
if let Some(meta) = metadata_store.get(ext_id) {
|
|
1384
|
+
if !self.matches_filter(meta, filter_conds).unwrap_or(false) {
|
|
1385
|
+
continue;
|
|
1386
|
+
}
|
|
1387
|
+
} else {
|
|
1388
|
+
continue;
|
|
1389
|
+
}
|
|
1390
|
+
}
|
|
1391
|
+
|
|
1392
|
+
let metadata = metadata_store.get(ext_id).cloned().unwrap_or_default();
|
|
1393
|
+
let vector_data = if return_vector {
|
|
1394
|
+
vector_store.get(ext_id).cloned()
|
|
1395
|
+
} else {
|
|
1396
|
+
None
|
|
1397
|
+
};
|
|
1398
|
+
|
|
1399
|
+
query_results.push((ext_id.clone(), neighbor.distance, metadata, vector_data));
|
|
1400
|
+
}
|
|
1401
|
+
}
|
|
1402
|
+
|
|
1403
|
+
query_results
|
|
1404
|
+
})
|
|
1405
|
+
.collect();
|
|
1406
|
+
|
|
1407
|
+
results
|
|
1408
|
+
});
|
|
1409
|
+
|
|
1410
|
+
// Convert to Python objects (needs GIL)
|
|
1411
|
+
let mut output = Vec::with_capacity(rust_results.len());
|
|
1412
|
+
for batch_result in rust_results {
|
|
1413
|
+
let mut py_batch = Vec::with_capacity(batch_result.len());
|
|
1414
|
+
|
|
1415
|
+
for (id, score, metadata, vector_data) in batch_result {
|
|
1416
|
+
let dict = PyDict::new(py);
|
|
1417
|
+
dict.set_item("id", id)?;
|
|
1418
|
+
dict.set_item("score", score)?;
|
|
1419
|
+
dict.set_item("metadata", self.value_map_to_python(&metadata, py)?)?;
|
|
1420
|
+
|
|
1421
|
+
if let Some(vec) = vector_data {
|
|
1422
|
+
dict.set_item("vector", vec)?;
|
|
1423
|
+
}
|
|
1424
|
+
|
|
1425
|
+
py_batch.push(dict.into());
|
|
1426
|
+
}
|
|
1427
|
+
|
|
1428
|
+
output.push(py_batch);
|
|
1429
|
+
}
|
|
1430
|
+
|
|
1431
|
+
Ok(output)
|
|
1432
|
+
}
|
|
1433
|
+
|
|
1434
|
+
|
|
1435
|
+
|
|
1436
|
+
|
|
1437
|
+
|
|
1438
|
+
|
|
1128
1439
|
}
|
|
File without changes
|
|
File without changes
|
{zeusdb_vector_database-0.1.1 → zeusdb_vector_database-0.1.2}/src/zeusdb_vector_database/py.typed
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|