1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
//! `VelesCollection` — UniFFI-exported collection operations for mobile.
use velesdb_core::VectorCollection as CoreCollection;
use crate::types::{
IndividualSearchRequest, MobileAdvancedConfig, MobileCollectionDiagnostics,
MobileCollectionStats, MobileIndexInfo, MobileQueryLimits, MobileStreamingConfig,
SearchQuality, SearchResult, VelesError, VelesPoint,
};
// ============================================================================
// Collection
// ============================================================================
/// A collection of vectors with associated metadata.
#[derive(uniffi::Object)]
pub struct VelesCollection {
pub(crate) inner: CoreCollection,
}
#[uniffi::export]
impl VelesCollection {
/// Searches for the k nearest neighbors to the query vector.
///
/// # Arguments
///
/// * `vector` - Query vector
/// * `limit` - Maximum number of results to return
///
/// # Returns
///
/// Vector of search results sorted by similarity.
pub fn search(&self, vector: Vec<f32>, limit: u32) -> Result<Vec<SearchResult>, VelesError> {
let results = self
.inner
.search_ids(&vector, usize::try_from(limit).unwrap_or(usize::MAX))?;
Ok(results
.into_iter()
.map(|sr| SearchResult {
id: sr.id,
score: sr.score,
payload: None,
})
.collect())
}
/// Searches with a specific quality profile controlling recall/latency.
///
/// # Arguments
///
/// * `vector` - Query vector
/// * `limit` - Maximum number of results to return
/// * `quality` - Search quality profile (Fast, Balanced, Accurate, etc.)
///
/// # Returns
///
/// Vector of search results sorted by similarity.
pub fn search_with_quality(
&self,
vector: Vec<f32>,
limit: u32,
quality: SearchQuality,
) -> Result<Vec<SearchResult>, VelesError> {
let core_quality: velesdb_core::SearchQuality = quality.into();
let results = self.inner.search_with_quality(
&vector,
usize::try_from(limit).unwrap_or(usize::MAX),
core_quality,
)?;
Ok(results
.into_iter()
.map(|sr| SearchResult {
id: sr.point.id,
score: sr.score,
payload: None,
})
.collect())
}
/// Inserts or updates a single point.
///
/// # Arguments
///
/// * `point` - The point to upsert
pub fn upsert(&self, point: VelesPoint) -> Result<(), VelesError> {
let core_point = parse_point(point)?;
self.inner.upsert(vec![core_point])?;
Ok(())
}
/// Inserts or updates multiple points in batch.
///
/// # Arguments
///
/// * `points` - Points to upsert
pub fn upsert_batch(&self, points: Vec<VelesPoint>) -> Result<(), VelesError> {
let core_points: Result<Vec<velesdb_core::Point>, VelesError> =
points.into_iter().map(parse_point).collect();
self.inner.upsert(core_points?)?;
Ok(())
}
/// Deletes a point by ID.
pub fn delete(&self, id: u64) -> Result<(), VelesError> {
self.inner.delete(&[id])?;
Ok(())
}
/// Returns the number of points in the collection.
#[allow(clippy::cast_possible_truncation)]
pub fn count(&self) -> u64 {
self.inner.config().point_count as u64
}
/// Returns the vector dimension.
#[allow(clippy::cast_possible_truncation)]
pub fn dimension(&self) -> u32 {
self.inner.config().dimension as u32
}
/// Gets points by their IDs.
///
/// # Arguments
///
/// * `ids` - List of point IDs to retrieve
///
/// # Returns
///
/// Vector of points found. Missing IDs are silently skipped.
pub fn get(&self, ids: Vec<u64>) -> Vec<VelesPoint> {
self.inner
.get(&ids)
.into_iter()
.flatten()
.map(|p| VelesPoint {
id: p.id,
vector: p.vector,
payload: p.payload.map(|v| v.to_string()),
})
.collect()
}
/// Gets a single point by ID.
///
/// # Arguments
///
/// * `id` - Point ID to retrieve
///
/// # Returns
///
/// The point if found, None otherwise.
pub fn get_by_id(&self, id: u64) -> Option<VelesPoint> {
self.inner
.get(&[id])
.into_iter()
.flatten()
.next()
.map(|p| VelesPoint {
id: p.id,
vector: p.vector,
payload: p.payload.map(|v| v.to_string()),
})
}
/// Checks if this is a metadata-only collection.
pub fn is_metadata_only(&self) -> bool {
self.inner.config().metadata_only
}
/// Performs full-text search using BM25.
///
/// # Arguments
///
/// * `query` - Text query to search for
/// * `limit` - Maximum number of results to return
///
/// # Returns
///
/// Vector of search results sorted by BM25 score.
pub fn text_search(&self, query: String, limit: u32) -> Result<Vec<SearchResult>, VelesError> {
let results = self
.inner
.text_search(&query, usize::try_from(limit).unwrap_or(usize::MAX))
.map_err(|e| VelesError::database(format!("Text search failed: {e}")))?;
Ok(results
.into_iter()
.map(|r| SearchResult {
id: r.point.id,
score: r.score,
payload: None,
})
.collect())
}
/// Performs hybrid search combining vector similarity and BM25 text search.
///
/// # Arguments
///
/// * `vector` - Query vector for similarity search
/// * `text_query` - Text query for BM25 search
/// * `limit` - Maximum number of results
/// * `vector_weight` - Weight for vector similarity (0.0-1.0)
///
/// # Returns
///
/// Vector of search results sorted by fused score.
pub fn hybrid_search(
&self,
vector: Vec<f32>,
text_query: String,
limit: u32,
vector_weight: f32,
) -> Result<Vec<SearchResult>, VelesError> {
let results = self.inner.hybrid_search(
&vector,
&text_query,
usize::try_from(limit).unwrap_or(usize::MAX),
Some(vector_weight),
)?;
Ok(results
.into_iter()
.map(|r| SearchResult {
id: r.point.id,
score: r.score,
payload: None,
})
.collect())
}
/// Searches with metadata filtering.
///
/// # Arguments
///
/// * `vector` - Query vector
/// * `limit` - Maximum number of results
/// * `filter_json` - JSON filter string (e.g., `{"condition": {"type": "eq", "field": "category", "value": "tech"}}`)
///
/// # Returns
///
/// Vector of search results matching the filter.
pub fn search_with_filter(
&self,
vector: Vec<f32>,
limit: u32,
filter_json: String,
) -> Result<Vec<SearchResult>, VelesError> {
// Parse filter JSON
let filter: velesdb_core::Filter = serde_json::from_str(&filter_json)
.map_err(|e| VelesError::database(format!("Invalid filter JSON: {e}")))?;
let results = self.inner.search_with_filter(
&vector,
usize::try_from(limit).unwrap_or(usize::MAX),
&filter,
)?;
Ok(results
.into_iter()
.map(|r| SearchResult {
id: r.point.id,
score: r.score,
payload: None,
})
.collect())
}
/// Performs batch search for multiple query vectors in parallel.
///
/// # Arguments
///
/// * `searches` - List of search requests
///
/// # Returns
///
/// List of result lists (one per query vector).
pub fn batch_search(
&self,
searches: Vec<IndividualSearchRequest>,
) -> Result<Vec<Vec<SearchResult>>, VelesError> {
let query_refs: Vec<&[f32]> = searches.iter().map(|s| s.vector.as_slice()).collect();
let filters: Result<Vec<Option<velesdb_core::Filter>>, VelesError> = searches
.iter()
.map(|s| {
s.filter
.as_ref()
.map(|f_json| {
serde_json::from_str(f_json).map_err(|e| {
VelesError::database(format!("Invalid filter JSON in batch: {e}"))
})
})
.transpose()
})
.collect();
let filters = filters?;
let max_top_k = searches.iter().map(|s| s.top_k).max().unwrap_or(10);
let all_results = self.inner.search_batch_with_filters(
&query_refs,
usize::try_from(max_top_k).unwrap_or(usize::MAX),
&filters,
)?;
Ok(all_results
.into_iter()
.zip(searches)
.map(
|(results, s): (Vec<velesdb_core::SearchResult>, IndividualSearchRequest)| {
results
.into_iter()
.take(usize::try_from(s.top_k).unwrap_or(usize::MAX))
.map(|r| SearchResult {
id: r.point.id,
score: r.score,
payload: None,
})
.collect()
},
)
.collect())
}
/// Performs text search with metadata filtering.
///
/// # Arguments
///
/// * `query` - Text query
/// * `limit` - Maximum number of results
/// * `filter_json` - JSON filter string
pub fn text_search_with_filter(
&self,
query: String,
limit: u32,
filter_json: String,
) -> Result<Vec<SearchResult>, VelesError> {
let filter: velesdb_core::Filter = serde_json::from_str(&filter_json)
.map_err(|e| VelesError::database(format!("Invalid filter JSON: {e}")))?;
let results = self
.inner
.text_search_with_filter(
&query,
usize::try_from(limit).unwrap_or(usize::MAX),
&filter,
)
.map_err(|e| VelesError::database(format!("Text search with filter failed: {e}")))?;
Ok(results
.into_iter()
.map(|r| SearchResult {
id: r.point.id,
score: r.score,
payload: None,
})
.collect())
}
/// Performs hybrid search with metadata filtering.
///
/// # Arguments
///
/// * `vector` - Query vector
/// * `text_query` - Text query
/// * `limit` - Maximum number of results
/// * `vector_weight` - Weight for vector similarity (0.0-1.0)
/// * `filter_json` - JSON filter string
pub fn hybrid_search_with_filter(
&self,
vector: Vec<f32>,
text_query: String,
limit: u32,
vector_weight: f32,
filter_json: String,
) -> Result<Vec<SearchResult>, VelesError> {
let filter: velesdb_core::Filter = serde_json::from_str(&filter_json)
.map_err(|e| VelesError::database(format!("Invalid filter JSON: {e}")))?;
let results = self.inner.hybrid_search_with_filter(
&vector,
&text_query,
usize::try_from(limit).unwrap_or(usize::MAX),
Some(vector_weight),
&filter,
)?;
Ok(results
.into_iter()
.map(|r| SearchResult {
id: r.point.id,
score: r.score,
payload: None,
})
.collect())
}
/// Executes a VelesQL query.
///
/// # Arguments
///
/// * `query_str` - VelesQL query string
/// * `params_json` - Optional JSON object with query parameters
///
/// # Returns
///
/// Vector of search results.
///
/// # Example
///
/// ```swift
/// let results = try collection.query(
/// "SELECT * FROM vectors WHERE category = 'tech' LIMIT 10",
/// nil
/// )
/// ```
pub fn query(
&self,
query_str: String,
params_json: Option<String>,
) -> Result<Vec<SearchResult>, VelesError> {
// Parse the VelesQL query
let parsed = velesdb_core::velesql::Parser::parse(&query_str)
.map_err(|e| VelesError::database(format!("VelesQL parse error: {}", e.message)))?;
// Parse params from JSON if provided
let params: std::collections::HashMap<String, serde_json::Value> = params_json
.map(|json| serde_json::from_str(&json))
.transpose()
.map_err(|e| VelesError::database(format!("Invalid params JSON: {e}")))?
.unwrap_or_default();
// Execute the query
let results = self
.inner
.execute_query(&parsed, ¶ms)
.map_err(|e| VelesError::database(format!("Query execution failed: {e}")))?;
Ok(results
.into_iter()
.map(|r| SearchResult {
id: r.point.id,
score: r.score,
payload: r.point.payload.as_ref().map(|p| p.to_string()),
})
.collect())
}
// multi_query_search and multi_query_search_with_filter are in collection_sparse.rs
/// Enables streaming ingestion on this collection.
///
/// Must be called before [`stream_insert`](Self::stream_insert); otherwise
/// stream inserts fail with "not configured". Calling it again replaces the
/// existing ingester.
///
/// # Arguments
///
/// * `config` - Optional [`MobileStreamingConfig`]. `None` uses the engine
/// defaults (`buffer_size=10000`, `batch_size=128`, `flush_interval_ms=50`).
pub fn enable_streaming(
&self,
config: Option<MobileStreamingConfig>,
) -> Result<(), VelesError> {
let core_config = config.map_or_else(velesdb_core::StreamingConfig::default, |c| {
velesdb_core::StreamingConfig::new(
usize::try_from(c.buffer_size).unwrap_or(usize::MAX),
usize::try_from(c.batch_size).unwrap_or(usize::MAX),
c.flush_interval_ms,
)
});
// Spawning the drain task needs an ambient runtime; enter the shared
// streaming runtime so the task is scheduled on it and survives this call.
let rt = crate::streaming_runtime::stream_runtime()?;
let _guard = rt.enter();
self.inner.enable_streaming(core_config);
Ok(())
}
/// Queues a batch of points for streaming ingestion.
///
/// Requires [`enable_streaming`](Self::enable_streaming) to have been called
/// first. Returns the number of points successfully queued.
///
/// # Arguments
///
/// * `points` - Points to queue for ingestion
pub fn stream_insert(&self, points: Vec<VelesPoint>) -> Result<u64, VelesError> {
let core_points: Result<Vec<velesdb_core::Point>, VelesError> =
points.into_iter().map(parse_point).collect();
let queued = self.inner.stream_insert_batch(core_points?).map_err(|e| {
VelesError::database(format!(
"Stream insert failed (buffer full or not configured): {e}"
))
})?;
Ok(u64::try_from(queued).unwrap_or(u64::MAX))
}
/// Flushes collection data to durable storage.
pub fn flush(&self) -> Result<(), VelesError> {
self.inner.flush()?;
Ok(())
}
/// Compacts on-disk storage, reclaiming space left by deleted vectors.
///
/// Returns the number of bytes reclaimed.
pub fn compact_storage(&self) -> Result<u64, VelesError> {
Ok(u64::try_from(self.inner.compact_storage()?).unwrap_or(u64::MAX))
}
/// Returns the current query guardrail limits for this collection.
pub fn guard_rails(&self) -> MobileQueryLimits {
self.inner.guard_rails().limits().into()
}
/// Applies post-creation overrides to advanced configuration fields
/// (`pq_rescore_oversampling`, `deferred_indexing`,
/// `async_index_builder`) and persists the updated config. Each `Some`
/// field is applied; each `None` field is left unchanged.
pub fn apply_advanced_config(&self, config: MobileAdvancedConfig) -> Result<(), VelesError> {
self.inner.apply_advanced_config(
config.pq_rescore_oversampling.map(Some),
config.deferred_indexing.map(|c| Some(c.into())),
config.async_index_builder.map(|c| Some(c.into())),
)?;
Ok(())
}
/// Returns all point IDs currently present in the collection.
pub fn all_ids(&self) -> Vec<u64> {
self.inner.all_ids()
}
/// Creates a secondary metadata index for a payload field.
pub fn create_index(&self, field_name: String) -> Result<(), VelesError> {
self.inner.create_index(&field_name)?;
Ok(())
}
/// Checks whether a secondary metadata index exists for a field.
pub fn has_secondary_index(&self, field_name: String) -> bool {
self.inner.has_secondary_index(&field_name)
}
/// Creates a graph/property index for equality lookups.
pub fn create_property_index(&self, label: String, property: String) -> Result<(), VelesError> {
self.inner.create_property_index(&label, &property)?;
Ok(())
}
/// Creates a graph/range index for range queries.
pub fn create_range_index(&self, label: String, property: String) -> Result<(), VelesError> {
self.inner.create_range_index(&label, &property)?;
Ok(())
}
/// Checks if a property index exists.
pub fn has_property_index(&self, label: String, property: String) -> bool {
self.inner.has_property_index(&label, &property)
}
/// Checks if a range index exists.
pub fn has_range_index(&self, label: String, property: String) -> bool {
self.inner.has_range_index(&label, &property)
}
/// Lists all index definitions on this collection.
pub fn list_indexes(&self) -> Vec<MobileIndexInfo> {
self.inner
.list_indexes()
.into_iter()
.map(MobileIndexInfo::from)
.collect()
}
/// Drops an index and returns true when something was removed.
pub fn drop_index(&self, label: String, property: String) -> Result<bool, VelesError> {
Ok(self.inner.drop_index(&label, &property)?)
}
/// Returns total memory usage used by indexes.
pub fn indexes_memory_usage(&self) -> u64 {
u64::try_from(self.inner.indexes_memory_usage()).unwrap_or(u64::MAX)
}
/// Runs ANALYZE and returns fresh statistics for this collection.
pub fn analyze(&self) -> Result<MobileCollectionStats, VelesError> {
Ok(self.inner.analyze()?.into())
}
/// Returns the latest known collection statistics snapshot.
pub fn get_stats(&self) -> MobileCollectionStats {
self.inner.get_stats().into()
}
/// Returns a health/readiness diagnostics snapshot for this collection.
pub fn diagnostics(&self) -> MobileCollectionDiagnostics {
self.inner.diagnostics().into()
}
}
/// Converts a [`VelesPoint`] into a core point, parsing the optional JSON payload.
fn parse_point(p: VelesPoint) -> Result<velesdb_core::Point, VelesError> {
let payload = p
.payload
.map(|s| serde_json::from_str(&s))
.transpose()
.map_err(|e| VelesError::database(format!("Invalid JSON payload: {e}")))?;
Ok(velesdb_core::Point::new(p.id, p.vector, payload))
}
// Sparse vector operations are in collection_sparse.rs