Skip to main content

reddb_server/storage/unified/dsl/
mod.rs

1//! Query DSL for Multi-Modal Queries
2//!
3//! Provides a fluent, chainable API for querying across Tables, Graphs, and Vectors
4//! in the Unified Storage Layer. Designed for maximum developer experience (DevX).
5//!
6//! # Design Principles
7//!
8//! 1. **Chainable**: Every method returns `self` for fluent chaining
9//! 2. **Type-Safe**: Compile-time checks for query structure
10//! 3. **Expressive**: Read like natural language
11//! 4. **Multi-Modal**: Seamlessly combine vector, graph, and table operations
12//!
13//! # Examples
14//!
15//! ```ignore
16//! use reddb::storage::dsl::*;
17//!
18//! // Vector similarity + metadata filter
19//! let results = Q::similar_to(&embedding, 10)
20//!     .in_collection("vulnerabilities")
21//!     .where_("severity").equals("critical")
22//!     .where_("cvss").greater_than(8.0)
23//!     .execute(&store)?;
24//!
25//! // Graph traversal + vector ranking
26//! let paths = Q::from_node("web-server-1")
27//!     .traverse("CONNECTS_TO")
28//!     .depth(3)
29//!     .ranked_by(&attack_vector_embedding)
30//!     .execute(&store)?;
31//!
32//! // Combined: find similar CVEs, expand to affected hosts
33//! let context = Q::similar_to(&cve_embedding, 5)
34//!     .expand_via(RefType::VectorToNode)
35//!     .expand_via(RefType::NodeToRow)
36//!     .with_weights(vector: 0.6, graph: 0.3, table: 0.1)
37//!     .execute(&store)?;
38//! ```
39
40mod builders;
41mod cross_modal;
42mod execution;
43mod filters;
44mod helpers;
45mod types;
46
47#[cfg(test)]
48mod tests;
49
50// Re-exports
51pub use builders::TextSearchBuilder;
52pub use builders::{
53    CrossModalWeights, GraphPatternDsl, GraphQueryBuilder, GraphStartPoint, HybridQueryBuilder,
54    JoinPhase, JoinStep, KvQueryBuilder, NodePatternDsl, QueryWeights, RefQueryBuilder,
55    ScanQueryBuilder, SortOrder, TableQueryBuilder, ThreeWayJoinBuilder, TraversalDirection,
56    TraversalStep, VectorQueryBuilder,
57};
58pub use filters::{Filter, FilterAcceptor, FilterOp, FilterValue, WhereClause};
59pub use helpers::{apply_filters, cosine_similarity};
60pub use types::{MatchComponents, QueryResult, ScoredMatch};
61
62use super::entity::{EntityId, RefType};
63
64// ============================================================================
65// Query Builder Entry Point
66// ============================================================================
67
68/// Query builder entry point. Start all queries with `Q::`.
69///
70/// # Examples
71///
72/// ```ignore
73/// // Vector similarity search
74/// Q::similar_to(&embedding, 10)
75///
76/// // Start from a graph node
77/// Q::from_node("node-label")
78///
79/// // Filter table rows
80/// Q::table("hosts").where_("status").equals("active")
81///
82/// // Full collection scan
83/// Q::all_in("vulnerabilities")
84/// ```
85pub struct Q;
86
87impl Q {
88    /// Start a vector similarity query
89    pub fn similar_to(vector: &[f32], k: usize) -> VectorQueryBuilder {
90        VectorQueryBuilder::new(vector.to_vec(), k)
91    }
92
93    /// Start a query from a specific graph node
94    pub fn from_node(label: impl Into<String>) -> GraphQueryBuilder {
95        GraphQueryBuilder::from_node(label)
96    }
97
98    /// Start a query from a specific entity by ID
99    pub fn from_id(id: EntityId) -> GraphQueryBuilder {
100        GraphQueryBuilder::from_id(id)
101    }
102
103    /// Query a specific table/collection
104    pub fn table(name: impl Into<String>) -> TableQueryBuilder {
105        TableQueryBuilder::new(name)
106    }
107
108    /// Shorthand for collection query
109    pub fn collection(name: impl Into<String>) -> TableQueryBuilder {
110        TableQueryBuilder::new(name)
111    }
112
113    /// Query all entities in a collection
114    pub fn all_in(collection: impl Into<String>) -> ScanQueryBuilder {
115        ScanQueryBuilder::new(collection)
116    }
117
118    /// Find entities by cross-reference
119    pub fn refs_from(id: EntityId, ref_type: RefType) -> RefQueryBuilder {
120        RefQueryBuilder::new(id, ref_type)
121    }
122
123    /// Text search across all indexed content
124    pub fn text_search(query: impl Into<String>) -> TextSearchBuilder {
125        TextSearchBuilder::new(query)
126    }
127
128    /// Query documents in a collection
129    ///
130    /// Documents are stored as enriched table rows, so this is a convenience
131    /// alias that delegates to `TableQueryBuilder`. The flattened top-level
132    /// document fields support path-based filtering through the table query DSL.
133    ///
134    /// # Example
135    /// ```ignore
136    /// let results = Q::document("articles")
137    ///     .where_("title").equals("Hello World")
138    ///     .limit(10)
139    ///     .execute(&store)?;
140    /// ```
141    pub fn document(collection: impl Into<String>) -> TableQueryBuilder {
142        TableQueryBuilder::new(collection)
143    }
144
145    /// Key-Value operations on a collection
146    ///
147    /// # Examples
148    /// ```ignore
149    /// // Get a value
150    /// let result = Q::kv("config").get("theme").execute(&store)?;
151    ///
152    /// // Set a value (upsert)
153    /// let result = Q::kv("config").set("theme", Value::text("dark")).execute(&store)?;
154    ///
155    /// // Delete a key
156    /// let result = Q::kv("config").delete("theme").execute(&store)?;
157    ///
158    /// // List all KV pairs
159    /// let result = Q::kv("config").list().execute(&store)?;
160    /// ```
161    pub fn kv(collection: impl Into<String>) -> KvQueryBuilder {
162        KvQueryBuilder::new(collection)
163    }
164
165    /// Hybrid query combining multiple modes
166    pub fn hybrid() -> HybridQueryBuilder {
167        HybridQueryBuilder::new()
168    }
169
170    /// Three-way cross-modal JOIN
171    ///
172    /// Efficiently chains queries across Vector → Graph → Table (or any order).
173    ///
174    /// # Example
175    /// ```ignore
176    /// // Find CVEs similar to vector, traverse to affected hosts, get host records
177    /// let results = Q::cross_modal()
178    ///     .start_vector(&cve_embedding, 10)
179    ///     .traverse("AFFECTS", 2)
180    ///     .join_table("hosts")
181    ///     .execute(&store)?;
182    /// ```
183    pub fn cross_modal() -> ThreeWayJoinBuilder {
184        ThreeWayJoinBuilder::new()
185    }
186}