Skip to main content

adk_rag/
vectorstore.rs

1//! Vector store trait for storing and searching vector embeddings.
2
3use std::collections::BTreeSet;
4
5use async_trait::async_trait;
6
7use crate::document::{Chunk, SearchResult};
8use crate::error::Result;
9use crate::filter::{Filter, validate_field_name};
10use crate::scope::Scope;
11
12/// How a collection is created.
13///
14/// `filterable` declares the metadata keys a [`Filter`] may name. A backend stores each as
15/// a column or field of its own where it needs one — LanceDB and Agent Retrieval do — and
16/// [`RagPipeline`](crate::RagPipeline) refuses a filter naming any other key with
17/// [`RagError::UnsupportedFilter`](crate::RagError::UnsupportedFilter) before any I/O.
18/// `document_id`, `source_uri`, and the chunk ID are always filterable.
19///
20/// # Example
21///
22/// ```rust
23/// use adk_rag::CollectionSpec;
24///
25/// let spec = CollectionSpec::new(768).with_filterable(["lang", "section"]);
26/// assert_eq!(spec.dimensions, 768);
27/// assert!(spec.filterable.contains("lang"));
28/// ```
29#[derive(Debug, Clone, PartialEq, Eq)]
30#[non_exhaustive]
31pub struct CollectionSpec {
32    /// The number of dimensions of every embedding stored in the collection.
33    pub dimensions: usize,
34    /// The metadata keys a filter may name.
35    pub filterable: BTreeSet<String>,
36}
37
38impl CollectionSpec {
39    /// A collection of `dimensions`-dimensional embeddings with no filterable metadata keys.
40    pub fn new(dimensions: usize) -> Self {
41        Self { dimensions, filterable: BTreeSet::new() }
42    }
43
44    /// Declares metadata keys a filter may name, in addition to any declared before.
45    ///
46    /// A key is 1 to [`MAX_FIELD_LEN`](crate::filter::MAX_FIELD_LEN) ASCII letters, digits,
47    /// and underscores, starting with a letter or underscore; `create_collection` rejects
48    /// any other key.
49    #[must_use]
50    pub fn with_filterable<I, S>(mut self, keys: I) -> Self
51    where
52        I: IntoIterator<Item = S>,
53        S: Into<String>,
54    {
55        self.filterable.extend(keys.into_iter().map(Into::into));
56        self
57    }
58
59    /// Checks every filterable key against the key rule.
60    ///
61    /// # Errors
62    ///
63    /// Returns [`RagError::UnsupportedFilter`](crate::RagError::UnsupportedFilter) naming the
64    /// first key outside the rule.
65    pub fn validate(&self) -> Result<()> {
66        self.filterable.iter().try_for_each(|key| validate_field_name(key))
67    }
68}
69
70/// A similarity search within one scope.
71///
72/// # Example
73///
74/// ```rust
75/// use adk_rag::{Field, Filter, VectorQuery};
76///
77/// let embedding = [0.1, 0.9];
78/// let english = Filter::eq(Field::metadata("lang"), "en");
79/// let query = VectorQuery::new(&embedding, 5).with_filter(&english);
80/// assert_eq!(query.top_k, 5);
81/// ```
82#[derive(Debug, Clone, Copy)]
83#[non_exhaustive]
84pub struct VectorQuery<'a> {
85    /// The query embedding.
86    pub embedding: &'a [f32],
87    /// The most results to return.
88    pub top_k: usize,
89    /// Only chunks the filter matches are candidates.
90    pub filter: Option<&'a Filter>,
91}
92
93impl<'a> VectorQuery<'a> {
94    /// A search for the `top_k` chunks nearest to `embedding`.
95    pub fn new(embedding: &'a [f32], top_k: usize) -> Self {
96        Self { embedding, top_k, filter: None }
97    }
98
99    /// Searches only the chunks `filter` matches; the filter applies before the top `k` are
100    /// chosen.
101    #[must_use]
102    pub fn with_filter(mut self, filter: &'a Filter) -> Self {
103        self.filter = Some(filter);
104        self
105    }
106}
107
108/// A storage backend for vector embeddings with similarity search.
109///
110/// Implementations manage named collections of [`Chunk`]s. Every operation on stored chunks
111/// names a [`Scope`], and a stored chunk is identified by its collection, its scope, and its
112/// chunk ID together:
113///
114/// - `upsert` replaces a chunk with the same ID in the same scope and never touches another
115///   scope's chunk with that ID.
116/// - `search` considers only the scope's chunks, applying the scope inside the backend's
117///   search before the top `k` are chosen, so a small scope beside a large one still gets
118///   its nearest chunks.
119/// - `delete`, `delete_where`, `count`, and `purge_scope` act on the scope's chunks only.
120///
121/// No operation reads, writes, or deletes across scopes, apart from `delete_collection`.
122///
123/// `search`, `count`, and `delete_where` take a [`Filter`], which the backend compiles into
124/// its own query language with bound parameters or typed expressions and applies with the
125/// scope, before the top `k` are chosen. A backend that cannot express a filter returns
126/// [`RagError::UnsupportedFilter`](crate::RagError::UnsupportedFilter) before any I/O, and so
127/// does every backend for a filter that fails [`Filter::validate`].
128///
129/// # Example
130///
131/// ```rust
132/// use adk_rag::{Chunk, CollectionSpec, InMemoryVectorStore, Scope, VectorQuery, VectorStore};
133///
134/// # #[tokio::main]
135/// # async fn main() -> adk_rag::Result<()> {
136/// let store = InMemoryVectorStore::new();
137/// store.create_collection("docs", &CollectionSpec::new(2)).await?;
138///
139/// let tenant_a = Scope::new("tenant-a")?;
140/// let tenant_b = Scope::new("tenant-b")?;
141/// let chunk = Chunk::new("doc_0", "doc", "tenant a's text").with_embedding(vec![1.0, 0.0]);
142/// store.upsert("docs", &tenant_a, &[chunk]).await?;
143///
144/// let query = VectorQuery::new(&[1.0, 0.0], 5);
145/// assert_eq!(store.search("docs", &tenant_a, &query).await?.len(), 1);
146/// assert!(store.search("docs", &tenant_b, &query).await?.is_empty());
147/// # Ok(())
148/// # }
149/// ```
150#[async_trait]
151pub trait VectorStore: Send + Sync {
152    /// Create a named collection. No-op if it already exists.
153    async fn create_collection(&self, name: &str, spec: &CollectionSpec) -> Result<()>;
154
155    /// Delete a named collection and every scope's data in it.
156    async fn delete_collection(&self, name: &str) -> Result<()>;
157
158    /// Upsert chunks into a scope of a collection. Chunks must have embeddings set.
159    async fn upsert(&self, collection: &str, scope: &Scope, chunks: &[Chunk]) -> Result<()>;
160
161    /// Delete a scope's chunks by their IDs. Unknown IDs are ignored.
162    async fn delete(&self, collection: &str, scope: &Scope, ids: &[&str]) -> Result<()>;
163
164    /// Search a scope for the `query.top_k` chunks most similar to `query.embedding` among
165    /// those `query.filter` matches.
166    ///
167    /// Returns results ordered by descending similarity score.
168    async fn search(
169        &self,
170        collection: &str,
171        scope: &Scope,
172        query: &VectorQuery<'_>,
173    ) -> Result<Vec<SearchResult>>;
174
175    /// The number of chunks a scope holds in a collection, or of those `filter` matches.
176    async fn count(&self, collection: &str, scope: &Scope, filter: Option<&Filter>) -> Result<u64>;
177
178    /// Delete the scope's chunks that `filter` matches, returning how many were deleted.
179    ///
180    /// The count is taken as the delete starts on backends whose delete reports no count.
181    /// [`purge_scope`](Self::purge_scope) is the only way to delete a whole scope.
182    async fn delete_where(&self, collection: &str, scope: &Scope, filter: &Filter) -> Result<u64>;
183
184    /// Delete every chunk of a scope in a collection, returning how many it held.
185    ///
186    /// The count is taken as the purge starts on backends whose delete reports no count.
187    async fn purge_scope(&self, collection: &str, scope: &Scope) -> Result<u64>;
188}