1use axum::{
8 extract::{Path, State},
9 response::IntoResponse,
10 Json,
11};
12use serde::{Deserialize, Serialize};
13use std::collections::HashMap;
14use std::sync::Arc;
15use utoipa::ToSchema;
16use velesdb_core::api_types::serde_id;
17use velesdb_core::Error;
18
19use crate::handlers::helpers::auto_core_error_response;
20use crate::types::{ErrorResponse, VELESQL_CONTRACT_VERSION};
21use crate::AppState;
22
23#[derive(Debug, Deserialize, ToSchema)]
25pub struct MatchQueryRequest {
26 pub query: String,
28 #[serde(default)]
30 pub params: HashMap<String, serde_json::Value>,
31 #[serde(default)]
33 pub vector: Option<Vec<f32>>,
34 #[serde(default)]
36 pub threshold: Option<f32>,
37}
38
39#[derive(Debug, Serialize, ToSchema)]
41pub struct MatchQueryResultItem {
42 #[serde(serialize_with = "serde_id::serialize_id_map_as_strings")]
44 #[cfg_attr(feature = "openapi", schema(schema_with = serde_id::id_map_schema))]
45 pub bindings: HashMap<String, u64>,
46 #[serde(skip_serializing_if = "Option::is_none")]
48 pub score: Option<f32>,
49 pub depth: u32,
51 #[serde(skip_serializing_if = "HashMap::is_empty")]
53 pub projected: HashMap<String, serde_json::Value>,
54}
55
56#[derive(Debug, Serialize, ToSchema)]
58pub struct MatchQueryResponse {
59 pub results: Vec<MatchQueryResultItem>,
61 pub took_ms: u64,
63 pub count: usize,
65 pub meta: MatchQueryMeta,
67}
68
69#[derive(Debug, Serialize, ToSchema)]
71pub struct MatchQueryMeta {
72 pub velesql_contract_version: String,
74}
75
76#[utoipa::path(
103 post,
104 path = "/collections/{name}/match",
105 tag = "graph",
106 params(("name" = String, Path, description = "Collection name")),
107 request_body = MatchQueryRequest,
108 responses(
109 (status = 200, description = "Match query results", body = MatchQueryResponse),
110 (status = 400, description = "Parse error or invalid query", body = ErrorResponse),
111 (status = 404, description = "Collection not found", body = ErrorResponse),
112 (status = 500, description = "Internal server error", body = ErrorResponse)
113 )
114)]
115pub async fn match_query(
116 Path(collection_name): Path<String>,
117 State(state): State<Arc<AppState>>,
118 Json(request): Json<MatchQueryRequest>,
119) -> axum::response::Response {
120 let state_clone = Arc::clone(&state);
124 let outcome = crate::handlers::helpers::run_blocking(move || {
125 run_match(&state_clone, &collection_name, &request)
126 })
127 .await;
128 match outcome {
129 Ok(Ok(response)) => Json(response).into_response(),
130 Ok(Err(e)) => auto_core_error_response(&e),
131 Err(resp) => resp,
132 }
133}
134
135fn run_match(
139 state: &AppState,
140 collection_name: &str,
141 request: &MatchQueryRequest,
142) -> Result<MatchQueryResponse, Error> {
143 let start = std::time::Instant::now();
144
145 let collection = resolve_match_collection(state, collection_name)
146 .ok_or_else(|| Error::CollectionNotFound(collection_name.to_string()))?;
147
148 let match_clause = parse_match_clause(&request.query)?;
149 validate_threshold(request.threshold)?;
150
151 if state
155 .db
156 .authorize_read(
157 collection_name,
158 velesdb_core::observer::QueryOperationKind::GraphTraversal,
159 None,
160 None,
161 )?
162 .is_some()
163 {
164 return Err(Error::Config(
165 "scope narrowing is not supported for MATCH queries".to_string(),
166 ));
167 }
168
169 let results = execute_match(&collection, &match_clause, request)?;
170
171 let count = results.len();
172 #[allow(clippy::cast_possible_truncation)]
173 let took_ms = start.elapsed().as_millis() as u64;
174
175 Ok(MatchQueryResponse {
176 results,
177 took_ms,
178 count,
179 meta: MatchQueryMeta {
180 velesql_contract_version: VELESQL_CONTRACT_VERSION.to_string(),
181 },
182 })
183}
184
185fn parse_match_clause(query_str: &str) -> Result<velesdb_core::velesql::MatchClause, Error> {
190 let query = velesdb_core::velesql::Parser::parse(query_str)?;
191 query.match_clause.ok_or_else(|| {
192 Error::Query(
193 "Query is not a MATCH query. Use MATCH (...) RETURN ... \
194 or call /query for SELECT statements."
195 .to_string(),
196 )
197 })
198}
199
200fn validate_threshold(threshold: Option<f32>) -> Result<(), Error> {
202 if let Some(t) = threshold {
203 if !(0.0..=1.0).contains(&t) {
204 return Err(Error::Query(format!(
205 "Invalid threshold: {t}. Must be between 0.0 and 1.0"
206 )));
207 }
208 }
209 Ok(())
210}
211
212enum MatchCollection {
213 Vector(velesdb_core::collection::VectorCollection),
214 Graph(velesdb_core::collection::GraphCollection),
215}
216
217fn resolve_match_collection(state: &AppState, name: &str) -> Option<MatchCollection> {
218 state
219 .db
220 .get_vector_collection(name)
221 .map(MatchCollection::Vector)
222 .or_else(|| {
223 state
224 .db
225 .get_graph_collection(name)
226 .map(MatchCollection::Graph)
227 })
228}
229
230fn execute_match(
231 collection: &MatchCollection,
232 match_clause: &velesdb_core::velesql::MatchClause,
233 request: &MatchQueryRequest,
234) -> Result<Vec<MatchQueryResultItem>, Error> {
235 let raw_results = if let Some(ref vector) = request.vector {
236 let threshold = request.threshold.unwrap_or(0.0);
237 match collection {
238 MatchCollection::Vector(coll) => {
239 coll.execute_match_with_similarity(match_clause, vector, threshold, &request.params)
240 }
241 MatchCollection::Graph(coll) => {
242 coll.execute_match_with_similarity(match_clause, vector, threshold, &request.params)
243 }
244 }
245 } else {
246 match collection {
247 MatchCollection::Vector(coll) => coll.execute_match(match_clause, &request.params),
248 MatchCollection::Graph(coll) => coll.execute_match(match_clause, &request.params),
249 }
250 };
251
252 raw_results.map(|results| {
253 results
254 .into_iter()
255 .map(|r| MatchQueryResultItem {
256 bindings: r.bindings,
257 score: r.score,
258 depth: r.depth,
259 projected: r.projected,
260 })
261 .collect()
262 })
263}
264
265#[cfg(test)]
266#[path = "match_query_tests.rs"]
267mod tests;