pub struct Collection { /* private fields */ }Expand description
A collection of vectors with associated metadata.
Implementations§
Source§impl Collection
impl Collection
Sourcepub fn upsert(&self, points: impl IntoIterator<Item = Point>) -> Result<()>
pub fn upsert(&self, points: impl IntoIterator<Item = Point>) -> Result<()>
Inserts or updates points in the collection.
Accepts any iterator of points (Vec, slice, array, etc.)
§Errors
Returns an error if any point has a mismatched dimension, or if attempting to insert vectors into a metadata-only collection.
Sourcepub fn upsert_metadata(
&self,
points: impl IntoIterator<Item = Point>,
) -> Result<()>
pub fn upsert_metadata( &self, points: impl IntoIterator<Item = Point>, ) -> Result<()>
Inserts or updates metadata-only points (no vectors).
This method is for metadata-only collections. Points should have empty vectors and only contain payload data.
§Errors
Returns an error if storage operations fail.
Sourcepub fn upsert_bulk(&self, points: &[Point]) -> Result<usize>
pub fn upsert_bulk(&self, points: &[Point]) -> Result<usize>
Bulk insert optimized for high-throughput import.
§Performance
This method is optimized for bulk loading:
- Uses parallel HNSW insertion (rayon)
- Single flush at the end (not per-point)
- No HNSW index save (deferred for performance)
- ~15x faster than previous sequential approach on large batches (5000+)
- Benchmark: 25-30 Kvec/s on 768D vectors
§Errors
Returns an error if any point has a mismatched dimension.
Sourcepub fn len(&self) -> usize
pub fn len(&self) -> usize
Returns the number of points in the collection.
Perf: Uses cached point_count from config instead of acquiring storage lock
Source§impl Collection
impl Collection
Sourcepub fn add_edge(&self, edge: GraphEdge) -> Result<()>
pub fn add_edge(&self, edge: GraphEdge) -> Result<()>
Adds an edge to the collection’s knowledge graph.
§Arguments
edge- The edge to add (id, source, target, label, properties)
§Errors
Returns Error::EdgeExists if an edge with the same ID already exists.
§Example
use velesdb_core::collection::graph::GraphEdge;
let edge = GraphEdge::new(1, 100, 200, "KNOWS")?;
collection.add_edge(edge)?;Sourcepub fn get_all_edges(&self) -> Vec<GraphEdge>
pub fn get_all_edges(&self) -> Vec<GraphEdge>
Gets all edges from the collection’s knowledge graph.
Note: This iterates through all stored edges. For large graphs,
consider using get_edges_by_label or get_outgoing_edges for
more targeted queries.
§Returns
Vector of all edges in the graph (cloned).
Sourcepub fn get_edges_by_label(&self, label: &str) -> Vec<GraphEdge>
pub fn get_edges_by_label(&self, label: &str) -> Vec<GraphEdge>
Sourcepub fn get_outgoing_edges(&self, node_id: u64) -> Vec<GraphEdge>
pub fn get_outgoing_edges(&self, node_id: u64) -> Vec<GraphEdge>
Sourcepub fn get_incoming_edges(&self, node_id: u64) -> Vec<GraphEdge>
pub fn get_incoming_edges(&self, node_id: u64) -> Vec<GraphEdge>
Sourcepub fn traverse_bfs(
&self,
source: u64,
max_depth: u32,
rel_types: Option<&[&str]>,
limit: usize,
) -> Result<Vec<TraversalResult>>
pub fn traverse_bfs( &self, source: u64, max_depth: u32, rel_types: Option<&[&str]>, limit: usize, ) -> Result<Vec<TraversalResult>>
Traverses the graph using BFS from a source node.
§Arguments
source- Starting node IDmax_depth- Maximum traversal depthrel_types- Optional filter by relationship typeslimit- Maximum number of results
§Returns
Vector of traversal results with target nodes and paths.
§Errors
Returns an error if traversal fails.
Sourcepub fn traverse_dfs(
&self,
source: u64,
max_depth: u32,
rel_types: Option<&[&str]>,
limit: usize,
) -> Result<Vec<TraversalResult>>
pub fn traverse_dfs( &self, source: u64, max_depth: u32, rel_types: Option<&[&str]>, limit: usize, ) -> Result<Vec<TraversalResult>>
Traverses the graph using DFS from a source node.
§Arguments
source- Starting node IDmax_depth- Maximum traversal depthrel_types- Optional filter by relationship typeslimit- Maximum number of results
§Returns
Vector of traversal results with target nodes and paths.
§Errors
Returns an error if traversal fails.
Sourcepub fn get_node_degree(&self, node_id: u64) -> (usize, usize)
pub fn get_node_degree(&self, node_id: u64) -> (usize, usize)
Sourcepub fn remove_edge(&self, edge_id: u64) -> bool
pub fn remove_edge(&self, edge_id: u64) -> bool
Sourcepub fn edge_count(&self) -> usize
pub fn edge_count(&self) -> usize
Returns the total number of edges in the graph.
Sourcepub fn graph_schema(&self) -> Option<GraphSchema>
pub fn graph_schema(&self) -> Option<GraphSchema>
Returns the graph schema stored in the collection config, if any.
Sourcepub fn is_graph(&self) -> bool
pub fn is_graph(&self) -> bool
Returns true if this collection was created as a graph collection.
Sourcepub fn has_embeddings(&self) -> bool
pub fn has_embeddings(&self) -> bool
Returns true if this graph collection stores node embeddings.
Sourcepub fn traverse_bfs_config(
&self,
source_id: u64,
config: &TraversalConfig,
) -> Vec<TraversalResult>
pub fn traverse_bfs_config( &self, source_id: u64, config: &TraversalConfig, ) -> Vec<TraversalResult>
BFS traversal using the core bfs_stream iterator.
Sourcepub fn traverse_dfs_config(
&self,
source_id: u64,
config: &TraversalConfig,
) -> Vec<TraversalResult>
pub fn traverse_dfs_config( &self, source_id: u64, config: &TraversalConfig, ) -> Vec<TraversalResult>
DFS traversal (iterative) using TraversalConfig.
Sourcepub fn search_by_embedding(
&self,
query: &[f32],
k: usize,
) -> Result<Vec<SearchResult>>
pub fn search_by_embedding( &self, query: &[f32], k: usize, ) -> Result<Vec<SearchResult>>
Searches for similar graph nodes by embedding vector.
Only available if has_embeddings() returns true.
§Errors
Returns Error::VectorNotAllowed if no embeddings are configured,
or Error::DimensionMismatch if the query dimension is wrong.
Source§impl Collection
impl Collection
Sourcepub fn create_index(&self, field_name: &str) -> Result<()>
pub fn create_index(&self, field_name: &str) -> Result<()>
Creates a secondary metadata index for a payload field.
§Errors
Returns Ok(()) on success. Index creation is idempotent.
Sourcepub fn has_secondary_index(&self, field_name: &str) -> bool
pub fn has_secondary_index(&self, field_name: &str) -> bool
Checks whether a secondary metadata index exists for a field.
Sourcepub fn secondary_index_lookup(
&self,
field_name: &str,
value: &JsonValue,
) -> Option<Vec<u64>>
pub fn secondary_index_lookup( &self, field_name: &str, value: &JsonValue, ) -> Option<Vec<u64>>
Looks up matching point IDs for an indexed field value.
Sourcepub fn has_property_index(&self, label: &str, property: &str) -> bool
pub fn has_property_index(&self, label: &str, property: &str) -> bool
Check if a property index exists.
Sourcepub fn has_range_index(&self, label: &str, property: &str) -> bool
pub fn has_range_index(&self, label: &str, property: &str) -> bool
Check if a range index exists.
Sourcepub fn list_indexes(&self) -> Vec<IndexInfo>
pub fn list_indexes(&self) -> Vec<IndexInfo>
List all indexes on this collection.
Sourcepub fn indexes_memory_usage(&self) -> usize
pub fn indexes_memory_usage(&self) -> usize
Get total memory usage of all indexes.
Source§impl Collection
impl Collection
Sourcepub fn create(
path: PathBuf,
dimension: usize,
metric: DistanceMetric,
) -> Result<Self>
pub fn create( path: PathBuf, dimension: usize, metric: DistanceMetric, ) -> Result<Self>
Creates a new collection at the specified path.
§Errors
Returns an error if the directory cannot be created or the config cannot be saved.
Sourcepub fn create_with_options(
path: PathBuf,
dimension: usize,
metric: DistanceMetric,
storage_mode: StorageMode,
) -> Result<Self>
pub fn create_with_options( path: PathBuf, dimension: usize, metric: DistanceMetric, storage_mode: StorageMode, ) -> Result<Self>
Creates a new collection with custom storage options.
§Arguments
path- Path to the collection directorydimension- Vector dimensionmetric- Distance metricstorage_mode- Vector storage mode (Full, SQ8, Binary)
§Errors
Returns an error if the directory cannot be created or the config cannot be saved.
Sourcepub fn create_typed(
path: PathBuf,
name: &str,
collection_type: &CollectionType,
) -> Result<Self>
pub fn create_typed( path: PathBuf, name: &str, collection_type: &CollectionType, ) -> Result<Self>
Sourcepub fn create_metadata_only(path: PathBuf, name: &str) -> Result<Self>
pub fn create_metadata_only(path: PathBuf, name: &str) -> Result<Self>
Creates a new metadata-only collection (no vectors, no HNSW index).
Metadata-only collections are optimized for storing reference data,
catalogs, and other non-vector data. They support CRUD operations
and VelesQL queries on payload, but NOT vector search.
§Errors
Returns an error if the directory cannot be created or the config cannot be saved.
Sourcepub fn is_metadata_only(&self) -> bool
pub fn is_metadata_only(&self) -> bool
Returns true if this is a metadata-only collection.
Sourcepub fn open(path: PathBuf) -> Result<Self>
pub fn open(path: PathBuf) -> Result<Self>
Opens an existing collection from the specified path.
§Errors
Returns an error if the config file cannot be read or parsed.
§INVARIANT(CACHE-01): write_generation starts at 0 on open
Every call to Collection::open initialises write_generation to 0.
This is safe for cache correctness because:
-
The plan cache is not persisted across process restarts — it is always empty when the database opens. There are therefore no stale cached plans that could be incorrectly served.
-
Database::load_collectionsbumpsschema_versionafter loading at least one collection (C-3). Any plan key built before the load would carry the pre-loadschema_versionand would miss the cache even if thewrite_generationhappened to match. -
Within a single process lifetime the
write_generationis only ever incremented (never reset), so a cache key built with generation N will never be reused once the generation advances past N.
Sourcepub fn create_graph_collection(
path: PathBuf,
name: &str,
schema: GraphSchema,
embedding_dim: Option<usize>,
metric: DistanceMetric,
) -> Result<Self>
pub fn create_graph_collection( path: PathBuf, name: &str, schema: GraphSchema, embedding_dim: Option<usize>, metric: DistanceMetric, ) -> Result<Self>
Creates a new graph collection (with optional node embeddings).
Persists graph_schema and embedding_dimension in config.json.
§Errors
Returns an error if the directory cannot be created or the config cannot be saved.
Sourcepub fn config(&self) -> CollectionConfig
pub fn config(&self) -> CollectionConfig
Returns the collection configuration.
Source§impl Collection
impl Collection
Sourcepub fn analyze(&self) -> Result<CollectionStats, Error>
pub fn analyze(&self) -> Result<CollectionStats, Error>
Analyzes the collection and returns statistics.
This method collects:
- Row count and deleted count
- Index statistics (HNSW entry count)
§Example
let stats = collection.analyze()?;
println!("Row count: {}", stats.row_count);
println!("Deletion ratio: {:.1}%", stats.deletion_ratio() * 100.0);§Errors
Returns an error if statistics cannot be collected.
§Panics
Panics if point_count exceeds u64::MAX (extremely unlikely on 64-bit systems).
Sourcepub fn get_stats(&self) -> CollectionStats
pub fn get_stats(&self) -> CollectionStats
Returns cached statistics if available and fresh, otherwise recomputes.
Results are cached for 30 seconds (STATS_TTL) to avoid re-scanning payload
storage on every execute_query() call. Mutating methods (upsert,
delete, etc.) invalidate the cache so the next call always recomputes.
§Note
Returns default stats on error (intentional for convenience).
Use analyze() directly if error handling is required.
Sourcepub fn estimate_column_selectivity(&self, column: &str) -> f64
pub fn estimate_column_selectivity(&self, column: &str) -> f64
Returns the selectivity estimate for a column.
Selectivity is 1/cardinality, representing the probability that a random row matches a specific value.
Source§impl Collection
impl Collection
Sourcepub fn search_batch_with_filters(
&self,
queries: &[&[f32]],
k: usize,
filters: &[Option<Filter>],
) -> Result<Vec<Vec<SearchResult>>>
pub fn search_batch_with_filters( &self, queries: &[&[f32]], k: usize, filters: &[Option<Filter>], ) -> Result<Vec<Vec<SearchResult>>>
Performs batch search for multiple query vectors in parallel with metadata filtering. Supports a different filter for each query in the batch.
§Arguments
queries- List of query vector slicesk- Maximum number of results per queryfilters- List of optional filters (must match queries length)
§Returns
Vector of search results for each query, matching its respective filter.
§Errors
Returns an error if queries and filters have different lengths or dimension mismatch.
Sourcepub fn search_batch_with_filter(
&self,
queries: &[&[f32]],
k: usize,
filter: &Filter,
) -> Result<Vec<Vec<SearchResult>>>
pub fn search_batch_with_filter( &self, queries: &[&[f32]], k: usize, filter: &Filter, ) -> Result<Vec<Vec<SearchResult>>>
Sourcepub fn search_batch_parallel(
&self,
queries: &[&[f32]],
k: usize,
) -> Result<Vec<Vec<SearchResult>>>
pub fn search_batch_parallel( &self, queries: &[&[f32]], k: usize, ) -> Result<Vec<Vec<SearchResult>>>
Performs batch search for multiple query vectors in parallel.
This method is optimized for high throughput using parallel index traversal.
§Arguments
queries- List of query vector slicesk- Maximum number of results per query
§Returns
Vector of search results for each query, with full point data.
§Errors
Returns an error if any query vector dimension doesn’t match the collection.
Sourcepub fn multi_query_search(
&self,
vectors: &[&[f32]],
top_k: usize,
fusion: FusionStrategy,
filter: Option<&Filter>,
) -> Result<Vec<SearchResult>>
pub fn multi_query_search( &self, vectors: &[&[f32]], top_k: usize, fusion: FusionStrategy, filter: Option<&Filter>, ) -> Result<Vec<SearchResult>>
Performs multi-query search with result fusion.
This method executes parallel searches for multiple query vectors and fuses the results using the specified fusion strategy. Ideal for Multiple Query Generation (MQG) pipelines where multiple reformulations of a user query are searched simultaneously.
§Arguments
vectors- Slice of query vectors (all must have same dimension)top_k- Maximum number of results to return after fusionfusion- Strategy for combining results (Average, Maximum, RRF, Weighted)filter- Optional metadata filter to apply to all queries
§Returns
Vector of SearchResult sorted by fused score descending.
§Errors
Returns an error if:
vectorsis empty- Any vector has incorrect dimension
- More than 10 vectors are provided (configurable limit)
Sourcepub fn multi_query_search_ids(
&self,
vectors: &[&[f32]],
top_k: usize,
fusion: FusionStrategy,
) -> Result<Vec<(u64, f32)>>
pub fn multi_query_search_ids( &self, vectors: &[&[f32]], top_k: usize, fusion: FusionStrategy, ) -> Result<Vec<(u64, f32)>>
Performs multi-query search returning only IDs and fused scores.
This is a faster variant of multi_query_search that skips fetching
vector and payload data. Use when you only need document IDs.
§Arguments
vectors- Slice of query vectorstop_k- Maximum number of resultsfusion- Fusion strategy
§Returns
Vector of (id, fused_score) tuples sorted by score descending.
§Errors
Returns an error if vectors is empty, exceeds max limit, or has dimension mismatch.
Source§impl Collection
impl Collection
Sourcepub fn execute_aggregate(
&self,
query: &Query,
params: &HashMap<String, Value>,
) -> Result<Value>
pub fn execute_aggregate( &self, query: &Query, params: &HashMap<String, Value>, ) -> Result<Value>
Execute an aggregation query and return results as JSON.
Supports COUNT(*), COUNT(column), SUM, AVG, MIN, MAX. Uses streaming aggregation - O(1) memory, single pass over data.
§Arguments
query- Parsed VelesQL query with aggregation functionsparams- Query parameters for placeholders
§Returns
JSON object with aggregation results, e.g.:
{"count": 100, "sum_price": 5000.0, "avg_rating": 4.5}§Errors
Returns an error when SELECT does not contain aggregations, when HAVING is used without GROUP BY, or when underlying scan/filter/aggregation operations fail.
Source§impl Collection
impl Collection
Sourcepub fn execute_match_with_similarity(
&self,
match_clause: &MatchClause,
query_vector: &[f32],
similarity_threshold: f32,
params: &HashMap<String, Value>,
) -> Result<Vec<MatchResult>>
pub fn execute_match_with_similarity( &self, match_clause: &MatchClause, query_vector: &[f32], similarity_threshold: f32, params: &HashMap<String, Value>, ) -> Result<Vec<MatchResult>>
Executes a MATCH query with similarity scoring (EPIC-045 US-003).
This method combines graph pattern matching with vector similarity,
enabling hybrid queries like:
MATCH (n:Article)-[:CITED]->(m) WHERE similarity(m.embedding, $query) > 0.8 RETURN m
§Arguments
match_clause- The parsed MATCH clausequery_vector- The query vector for similarity scoringsimilarity_threshold- Minimum similarity score (0.0 to 1.0)params- Query parameters
§Returns
Vector of MatchResult with similarity scores and projected properties.
§Errors
Returns an error on dimension mismatch, underlying storage/search errors,
or ORDER BY failures.
Sourcepub fn order_match_results(
&self,
results: &mut [MatchResult],
order_by: &str,
descending: bool,
)
pub fn order_match_results( &self, results: &mut [MatchResult], order_by: &str, descending: bool, )
Applies ORDER BY to match results (EPIC-045 US-005).
Supports ordering by:
similarity()- Vector similarity score- Property path (e.g.,
n.name) - Depth
Sourcepub fn match_results_to_search_results(
&self,
match_results: Vec<MatchResult>,
) -> Result<Vec<SearchResult>>
pub fn match_results_to_search_results( &self, match_results: Vec<MatchResult>, ) -> Result<Vec<SearchResult>>
Converts MatchResults to SearchResults for unified API (EPIC-045 US-002).
This allows MATCH queries to return the same result type as SELECT queries, enabling consistent downstream processing.
§Errors
Returns an error when vector storage access fails for any matched node.
Source§impl Collection
impl Collection
Sourcepub fn execute_match(
&self,
match_clause: &MatchClause,
params: &HashMap<String, Value>,
) -> Result<Vec<MatchResult>>
pub fn execute_match( &self, match_clause: &MatchClause, params: &HashMap<String, Value>, ) -> Result<Vec<MatchResult>>
Executes a MATCH query on this collection (EPIC-045 US-002).
This method performs graph pattern matching by:
- Finding start nodes matching the first node pattern
- Traversing relationships according to the pattern
- Filtering results by WHERE clause conditions
- Returning results according to RETURN clause
§Arguments
match_clause- The parsed MATCH clauseparams- Query parameters for resolving placeholders
§Returns
Vector of MatchResult containing matched nodes and their bindings.
§Errors
Returns an error if the query cannot be executed. Executes a MATCH query without guard-rail context (backward-compatible entry point).
Sourcepub fn execute_match_with_context(
&self,
match_clause: &MatchClause,
params: &HashMap<String, Value>,
ctx: Option<&QueryContext>,
) -> Result<Vec<MatchResult>>
pub fn execute_match_with_context( &self, match_clause: &MatchClause, params: &HashMap<String, Value>, ctx: Option<&QueryContext>, ) -> Result<Vec<MatchResult>>
Executes a MATCH query on this collection (EPIC-045 US-002, EPIC-048).
This method performs graph pattern matching by:
- Finding start nodes matching the first node pattern
- Traversing relationships according to the pattern
- Enforcing guard-rail limits (depth, cardinality, timeout) if a context is provided
- Filtering results by WHERE clause conditions
- Returning results according to RETURN clause
§Arguments
match_clause- The parsed MATCH clauseparams- Query parameters for resolving placeholdersctx- Optional guard-rail context for enforcing limits
§Errors
Returns an error if the query cannot be executed or a guard-rail is violated.
Source§impl Collection
impl Collection
Sourcepub fn execute_query(
&self,
query: &Query,
params: &HashMap<String, Value>,
) -> Result<Vec<SearchResult>>
pub fn execute_query( &self, query: &Query, params: &HashMap<String, Value>, ) -> Result<Vec<SearchResult>>
Executes a VelesQL query on this collection with the "default" client id.
This method unifies vector search, text search, and metadata filtering
into a single interface. For per-client rate limiting use
execute_query_with_client.
§Errors
Returns an error if the query cannot be executed (e.g., missing parameters).
Sourcepub fn execute_query_with_client(
&self,
query: &Query,
params: &HashMap<String, Value>,
client_id: &str,
) -> Result<Vec<SearchResult>>
pub fn execute_query_with_client( &self, query: &Query, params: &HashMap<String, Value>, client_id: &str, ) -> Result<Vec<SearchResult>>
Executes a VelesQL query with a specific client identifier for per-client rate limiting.
Each distinct client_id maintains an independent token bucket, so one
busy client cannot exhaust the quota of another.
§Errors
Returns an error if the query cannot be executed or a guard-rail fires.
Sourcepub fn execute_query_str(
&self,
sql: &str,
params: &HashMap<String, Value>,
) -> Result<Vec<SearchResult>>
pub fn execute_query_str( &self, sql: &str, params: &HashMap<String, Value>, ) -> Result<Vec<SearchResult>>
Parses and executes a VelesQL query string, using the collection-level parse cache (P1-A).
Equivalent to calling Parser::parse(sql) followed by execute_query(), but caches
parsed ASTs so repeated identical queries avoid re-parsing overhead.
§Arguments
sql- Raw VelesQL query stringparams- Query parameters for resolving placeholders (e.g.,$v)
§Errors
Returns a parse error if sql is invalid, or an execution error if the query fails.
Source§impl Collection
impl Collection
Sourcepub fn sparse_search_default(
&self,
query: &SparseVector,
k: usize,
) -> Result<Vec<SearchResult>>
pub fn sparse_search_default( &self, query: &SparseVector, k: usize, ) -> Result<Vec<SearchResult>>
Sparse-only search on the default sparse index.
§Errors
Returns an error if the default sparse index does not exist.
Sourcepub fn sparse_search_named(
&self,
query: &SparseVector,
k: usize,
index_name: &str,
) -> Result<Vec<SearchResult>>
pub fn sparse_search_named( &self, query: &SparseVector, k: usize, index_name: &str, ) -> Result<Vec<SearchResult>>
Sparse-only search on a named sparse index.
§Errors
Returns an error if the named sparse index does not exist.
Sourcepub fn hybrid_sparse_search(
&self,
dense_vector: &[f32],
sparse_query: &SparseVector,
k: usize,
strategy: &FusionStrategy,
) -> Result<Vec<SearchResult>>
pub fn hybrid_sparse_search( &self, dense_vector: &[f32], sparse_query: &SparseVector, k: usize, strategy: &FusionStrategy, ) -> Result<Vec<SearchResult>>
Hybrid dense+sparse search with RRF fusion on the default sparse index.
Runs both dense (HNSW) and sparse branches, then fuses using the provided strategy (typically RRF with k=60).
§Errors
Returns an error if the sparse index does not exist or fusion fails.
Source§impl Collection
impl Collection
Sourcepub fn text_search(&self, query: &str, k: usize) -> Vec<SearchResult>
pub fn text_search(&self, query: &str, k: usize) -> Vec<SearchResult>
Sourcepub fn text_search_with_filter(
&self,
query: &str,
k: usize,
filter: &Filter,
) -> Vec<SearchResult>
pub fn text_search_with_filter( &self, query: &str, k: usize, filter: &Filter, ) -> Vec<SearchResult>
Sourcepub fn hybrid_search(
&self,
vector_query: &[f32],
text_query: &str,
k: usize,
vector_weight: Option<f32>,
) -> Result<Vec<SearchResult>>
pub fn hybrid_search( &self, vector_query: &[f32], text_query: &str, k: usize, vector_weight: Option<f32>, ) -> Result<Vec<SearchResult>>
Performs hybrid search combining vector similarity and full-text search.
Uses Reciprocal Rank Fusion (RRF) to combine results from both searches.
§Arguments
vector_query- Query vector for similarity searchtext_query- Text query for BM25 searchk- Maximum number of results to returnvector_weight- Weight for vector results (0.0-1.0, default 0.5)
§Performance (v0.9+)
- Streaming RRF:
BinaryHeapmaintains top-k during fusion (O(n log k) vs O(n log n)) - Vector-first gating: Text search limited to 2k candidates for efficiency
FxHashMap: Faster hashing for score aggregation
§Errors
Returns an error if the query vector dimension doesn’t match.
Sourcepub fn hybrid_search_with_filter(
&self,
vector_query: &[f32],
text_query: &str,
k: usize,
vector_weight: Option<f32>,
filter: &Filter,
) -> Result<Vec<SearchResult>>
pub fn hybrid_search_with_filter( &self, vector_query: &[f32], text_query: &str, k: usize, vector_weight: Option<f32>, filter: &Filter, ) -> Result<Vec<SearchResult>>
Performs hybrid search (vector + text) with metadata filtering.
Uses Reciprocal Rank Fusion (RRF) to combine results from both searches, then applies metadata filter.
§Arguments
vector_query- Query vector for similarity searchtext_query- Text query for BM25 searchk- Maximum number of results to returnvector_weight- Weight for vector results (0.0-1.0, default 0.5)filter- Metadata filter to apply
§Errors
Returns an error if the query vector dimension doesn’t match.
Source§impl Collection
impl Collection
Sourcepub fn search(&self, query: &[f32], k: usize) -> Result<Vec<SearchResult>>
pub fn search(&self, query: &[f32], k: usize) -> Result<Vec<SearchResult>>
Searches for the k nearest neighbors of the query vector.
Uses HNSW index for fast approximate nearest neighbor search.
§Errors
Returns an error if the query vector dimension doesn’t match the collection,
or if this is a metadata-only collection (use query() instead).
Sourcepub fn search_with_ef(
&self,
query: &[f32],
k: usize,
ef_search: usize,
) -> Result<Vec<SearchResult>>
pub fn search_with_ef( &self, query: &[f32], k: usize, ef_search: usize, ) -> Result<Vec<SearchResult>>
Performs vector similarity search with custom ef_search parameter.
Higher ef_search = better recall, slower search.
Default ef_search is 128 (Balanced mode).
§Errors
Returns an error if the query vector dimension doesn’t match the collection.
Sourcepub fn search_ids(&self, query: &[f32], k: usize) -> Result<Vec<(u64, f32)>>
pub fn search_ids(&self, query: &[f32], k: usize) -> Result<Vec<(u64, f32)>>
Performs fast vector similarity search returning only IDs and scores.
Perf: This is ~3-5x faster than search() because it skips vector/payload retrieval.
Use this when you only need IDs and scores, not full point data.
§Arguments
query- Query vectork- Maximum number of results to return
§Returns
Vector of (id, score) tuples sorted by similarity.
§Errors
Returns an error if the query vector dimension doesn’t match the collection.
Sourcepub fn search_with_filter(
&self,
query: &[f32],
k: usize,
filter: &Filter,
) -> Result<Vec<SearchResult>>
pub fn search_with_filter( &self, query: &[f32], k: usize, filter: &Filter, ) -> Result<Vec<SearchResult>>
Searches for the k nearest neighbors with metadata filtering.
Performs post-filtering: retrieves more candidates from HNSW, then filters by metadata conditions.
§Arguments
query- Query vectork- Maximum number of results to returnfilter- Metadata filter to apply
§Errors
Returns an error if the query vector dimension doesn’t match the collection.
Source§impl Collection
impl Collection
Sourcepub fn stream_insert(&self, point: Point) -> Result<(), BackpressureError>
pub fn stream_insert(&self, point: Point) -> Result<(), BackpressureError>
Sends a point into the streaming ingestion channel.
Returns BackpressureError::NotConfigured if streaming is not active
on this collection.
§Errors
Returns BackpressureError on buffer-full or not-configured.
Sourcepub fn enable_streaming(&self, config: StreamingConfig)
pub fn enable_streaming(&self, config: StreamingConfig)
Enables streaming ingestion on this collection.
Creates a StreamIngester with the given config and stores it in
the stream_ingester field. Points can then be submitted via
stream_insert.
Calling this when streaming is already active replaces the existing
ingester (the old drain task is aborted via Drop).
Future: auto-enable from persisted StreamingConfig on open (STREAM-01)
Sourcepub fn push_to_delta_if_active(&self, entries: &[(u64, Vec<f32>)])
pub fn push_to_delta_if_active(&self, entries: &[(u64, Vec<f32>)])
Pushes entries into the delta buffer if it is currently active.
This is a convenience method for callers (e.g., the REST upsert handlers) that do not have direct access to the delta buffer internals.
No-op when the delta buffer is inactive.
Trait Implementations§
Source§impl Clone for Collection
impl Clone for Collection
Source§fn clone(&self) -> Collection
fn clone(&self) -> Collection
1.0.0 · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source. Read moreAuto Trait Implementations§
impl Freeze for Collection
impl !RefUnwindSafe for Collection
impl Send for Collection
impl Sync for Collection
impl Unpin for Collection
impl UnsafeUnpin for Collection
impl !UnwindSafe for Collection
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
Source§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self>
fn into_either(self, into_left: bool) -> Either<Self, Self>
self into a Left variant of Either<Self, Self>
if into_left is true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
self into a Left variant of Either<Self, Self>
if into_left(&self) returns true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§impl<T> Paint for Twhere
T: ?Sized,
impl<T> Paint for Twhere
T: ?Sized,
Source§fn fg(&self, value: Color) -> Painted<&T>
fn fg(&self, value: Color) -> Painted<&T>
Returns a styled value derived from self with the foreground set to
value.
This method should be used rarely. Instead, prefer to use color-specific
builder methods like red() and
green(), which have the same functionality but are
pithier.
§Example
Set foreground color to white using fg():
use yansi::{Paint, Color};
painted.fg(Color::White);Set foreground color to white using white().
use yansi::Paint;
painted.white();Source§fn bright_black(&self) -> Painted<&T>
fn bright_black(&self) -> Painted<&T>
Source§fn bright_red(&self) -> Painted<&T>
fn bright_red(&self) -> Painted<&T>
Source§fn bright_green(&self) -> Painted<&T>
fn bright_green(&self) -> Painted<&T>
Source§fn bright_yellow(&self) -> Painted<&T>
fn bright_yellow(&self) -> Painted<&T>
Source§fn bright_blue(&self) -> Painted<&T>
fn bright_blue(&self) -> Painted<&T>
Source§fn bright_magenta(&self) -> Painted<&T>
fn bright_magenta(&self) -> Painted<&T>
Source§fn bright_cyan(&self) -> Painted<&T>
fn bright_cyan(&self) -> Painted<&T>
Source§fn bright_white(&self) -> Painted<&T>
fn bright_white(&self) -> Painted<&T>
Source§fn bg(&self, value: Color) -> Painted<&T>
fn bg(&self, value: Color) -> Painted<&T>
Returns a styled value derived from self with the background set to
value.
This method should be used rarely. Instead, prefer to use color-specific
builder methods like on_red() and
on_green(), which have the same functionality but
are pithier.
§Example
Set background color to red using fg():
use yansi::{Paint, Color};
painted.bg(Color::Red);Set background color to red using on_red().
use yansi::Paint;
painted.on_red();Source§fn on_primary(&self) -> Painted<&T>
fn on_primary(&self) -> Painted<&T>
Source§fn on_magenta(&self) -> Painted<&T>
fn on_magenta(&self) -> Painted<&T>
Source§fn on_bright_black(&self) -> Painted<&T>
fn on_bright_black(&self) -> Painted<&T>
Source§fn on_bright_red(&self) -> Painted<&T>
fn on_bright_red(&self) -> Painted<&T>
Source§fn on_bright_green(&self) -> Painted<&T>
fn on_bright_green(&self) -> Painted<&T>
Source§fn on_bright_yellow(&self) -> Painted<&T>
fn on_bright_yellow(&self) -> Painted<&T>
Source§fn on_bright_blue(&self) -> Painted<&T>
fn on_bright_blue(&self) -> Painted<&T>
Source§fn on_bright_magenta(&self) -> Painted<&T>
fn on_bright_magenta(&self) -> Painted<&T>
Source§fn on_bright_cyan(&self) -> Painted<&T>
fn on_bright_cyan(&self) -> Painted<&T>
Source§fn on_bright_white(&self) -> Painted<&T>
fn on_bright_white(&self) -> Painted<&T>
Source§fn attr(&self, value: Attribute) -> Painted<&T>
fn attr(&self, value: Attribute) -> Painted<&T>
Enables the styling Attribute value.
This method should be used rarely. Instead, prefer to use
attribute-specific builder methods like bold() and
underline(), which have the same functionality
but are pithier.
§Example
Make text bold using attr():
use yansi::{Paint, Attribute};
painted.attr(Attribute::Bold);Make text bold using using bold().
use yansi::Paint;
painted.bold();Source§fn rapid_blink(&self) -> Painted<&T>
fn rapid_blink(&self) -> Painted<&T>
Source§fn quirk(&self, value: Quirk) -> Painted<&T>
fn quirk(&self, value: Quirk) -> Painted<&T>
Enables the yansi Quirk value.
This method should be used rarely. Instead, prefer to use quirk-specific
builder methods like mask() and
wrap(), which have the same functionality but are
pithier.
§Example
Enable wrapping using .quirk():
use yansi::{Paint, Quirk};
painted.quirk(Quirk::Wrap);Enable wrapping using wrap().
use yansi::Paint;
painted.wrap();Source§fn clear(&self) -> Painted<&T>
👎Deprecated since 1.0.1: renamed to resetting() due to conflicts with Vec::clear().
The clear() method will be removed in a future release.
fn clear(&self) -> Painted<&T>
resetting() due to conflicts with Vec::clear().
The clear() method will be removed in a future release.Source§fn whenever(&self, value: Condition) -> Painted<&T>
fn whenever(&self, value: Condition) -> Painted<&T>
Conditionally enable styling based on whether the Condition value
applies. Replaces any previous condition.
See the crate level docs for more details.
§Example
Enable styling painted only when both stdout and stderr are TTYs:
use yansi::{Paint, Condition};
painted.red().on_yellow().whenever(Condition::STDOUTERR_ARE_TTY);