use std::collections::{BTreeMap, HashSet};
use relate_core::{Error, Result, Value};
use relate_ir::{
Expr, PathPattern, PatternPayload, SearchClause, SearchIndexSpec, SearchKind, SearchSpec,
};
use relate_model::EntityKind;
use relate_names::SmallName;
use crate::ctx::ExecCtx;
use crate::eval::{eval, filter_rows_where_clause};
use crate::overlay::ExecGraph;
use crate::row::Row;
use super::fulltext;
use super::match_clause::{bind_pattern_nulls, MatchClauseInputs};
use super::pattern_policies::RowFold;
use super::vector::{self, vector_operand};
mod combine;
mod deferred;
mod direct;
mod growth;
use combine::combine_candidates;
use deferred::deferred_search_rows;
use direct::{direct_search_rows, pre_bound_search_rows};
fn invalid_value_type(detail: impl Into<String>) -> Error {
Error::ty(format!("InvalidValueType: {}", detail.into()))
}
fn check_binding_kind(binding: Option<EntityKind>, index: EntityKind) -> Result<()> {
match binding {
Some(kind) if kind == index => Ok(()),
Some(_) => Err(invalid_value_type(
"SEARCH binding entity does not match index",
)),
None => Err(invalid_value_type(
"SEARCH binding variable must be bound as a node or relationship",
)),
}
}
fn attach_score(row: &mut Row, score_var: Option<&SmallName>, score: Value) {
if let Some(score_var) = score_var {
row.insert(score_var.to_string(), score);
}
}
fn eval_window_int(
graph: &ExecGraph<'_>,
input: &Row,
expr: &Expr,
params: &BTreeMap<String, Value>,
clause: &str,
) -> Result<usize> {
match eval(graph, input, expr, params)? {
Value::Int(value) if (0..=i32::MAX as i64).contains(&value) => Ok(value as usize),
_ => Err(Error::syntax(format!(
"NumberOutOfRange: SEARCH {clause} must be an INTEGER NOT NULL"
))),
}
}
pub(super) struct SearchEnv<'a> {
ctx: ExecCtx<'a>,
corpora: fulltext::CorpusMemo,
}
struct RowSourceCtx<'a> {
clause: MatchClauseInputs<'a>,
binding_kind: Option<EntityKind>,
search: &'a SearchClause,
}
pub(super) struct SpecCandidates {
kind: EntityKind,
candidates: Vec<(Value, f64)>,
may_widen: bool,
}
fn optional_null_row(mut row: Row, patterns: &[PathPattern], score_var: Option<&SmallName>) -> Row {
bind_pattern_nulls(&mut row, patterns);
attach_score(&mut row, score_var, Value::Null);
row
}
#[derive(Clone, Copy, Debug)]
pub(super) enum Growth {
Fixed,
Widen(usize),
}
impl Growth {
fn extra_candidates(self) -> usize {
match self {
Growth::Fixed => 0,
Growth::Widen(extra) => extra,
}
}
}
fn search_spec_candidates(
env: &SearchEnv<'_>,
input: &Row,
spec: &SearchSpec,
window: SearchWindow,
growth: Growth,
) -> Result<Option<SpecCandidates>> {
match spec {
SearchSpec::Index(index) => {
search_index_candidates(env, input, index, window, growth.extra_candidates())
}
SearchSpec::Combine(combine) => combine_candidates(env, input, combine, window),
}
}
#[derive(Clone, Copy, Debug)]
pub(super) struct SearchWindow {
pub(super) skip: usize,
pub(super) limit: usize,
}
impl SearchWindow {
fn unbounded() -> Self {
Self {
skip: 0,
limit: usize::MAX,
}
}
fn satisfied(self, survivors: usize) -> bool {
survivors >= self.limit
}
fn empty_for_one_entity(self) -> bool {
self.skip > 0 || self.satisfied(0)
}
}
fn spec_window(env: &SearchEnv<'_>, input: &Row, spec: &SearchSpec) -> Result<SearchWindow> {
let ExecCtx { graph, params, .. } = env.ctx;
match spec {
SearchSpec::Index(index) => {
let limit = eval_window_int(graph, input, &index.limit_expr, params, "LIMIT")?;
let skip = match &index.offset_expr {
Some(expr) => eval_window_int(graph, input, expr.as_ref(), params, "SKIP/OFFSET")?,
None => 0,
};
Ok(SearchWindow { skip, limit })
}
SearchSpec::Combine(combine) => {
let limit = match &combine.limit_expr {
Some(expr) => eval_window_int(graph, input, expr, params, "LIMIT")?,
None => return Ok(SearchWindow::unbounded()),
};
Ok(SearchWindow { skip: 0, limit })
}
}
}
fn search_index_candidates(
env: &SearchEnv<'_>,
input: &Row,
index: &SearchIndexSpec,
window: SearchWindow,
extra_candidates: usize,
) -> Result<Option<SpecCandidates>> {
let ExecCtx { graph, params, .. } = env.ctx;
let fetch_depth = window
.skip
.saturating_add(window.limit)
.saturating_add(extra_candidates);
let query = eval(graph, input, &index.for_expr, params)?;
let (kind, candidates) = match index.kind {
SearchKind::Vector => {
let Some(query) = vector_operand(&query)? else {
return Ok(None);
};
vector::index_candidates(env.ctx, index, input, &query, fetch_depth)?
}
SearchKind::Fulltext => {
let Some(query) = fulltext::operand(&query)? else {
return Ok(None);
};
fulltext::index_candidates(env.ctx, &env.corpora, input, index, query, fetch_depth)?
}
};
let may_widen = candidates.len() == fetch_depth;
Ok(Some(SpecCandidates {
kind,
candidates,
may_widen,
}))
}
fn candidate_entity_id(candidate: &Value) -> Result<i64> {
match candidate {
Value::Node(node) => Ok(node.id),
Value::Relationship(rel) => Ok(rel.id),
_ => Err(Error::execution(
"InvalidValueType: SEARCH candidate is not a node or relationship",
)),
}
}
fn search_reads_pattern(search: &SearchClause, patterns: &[PathPattern]) -> bool {
let mut pattern_names = HashSet::new();
for pattern in patterns {
relate_ir::path_pattern_mentions(pattern, &mut pattern_names);
}
let mut spec_vars = HashSet::new();
for expr in search.spec.exprs() {
relate_ir::expr_vars(expr, &mut spec_vars);
}
spec_vars.iter().any(|name| pattern_names.contains(name))
}
fn path_pattern_binding_kind(patterns: &[PathPattern], name: &str) -> Option<EntityKind> {
patterns.iter().find_map(|pattern| {
let mut kind = None;
relate_ir::walk_pattern_payloads(pattern, &mut |payload| match payload {
PatternPayload::Node(node) if node.variable.as_ref().is_some_and(|v| v == name) => {
kind = kind.or(Some(EntityKind::Node));
}
PatternPayload::Relationship(rel)
if rel.variable.as_ref().is_some_and(|v| v == name) =>
{
kind = kind.or(Some(EntityKind::Relationship));
}
PatternPayload::Node(_)
| PatternPayload::Relationship(_)
| PatternPayload::Quantified(_) => {}
});
kind
})
}
pub(crate) fn search_match_clause(
ctx: ExecCtx<'_>,
rows: Vec<Row>,
clause: MatchClauseInputs<'_>,
search: &SearchClause,
fold: Option<&dyn RowFold>,
) -> Result<Vec<Row>> {
let MatchClauseInputs {
optional,
match_mode,
patterns,
where_clause,
} = clause;
let binding_kind = search
.binding_var
.with_str(|text| path_pattern_binding_kind(patterns, text));
let reads_pattern = search_reads_pattern(search, patterns);
let corpora = fulltext::CorpusMemo::new(ctx.graph);
let env = SearchEnv { ctx, corpora };
let mut out = Vec::new();
for input in rows {
let mut matched = if reads_pattern {
deferred_search_rows(
&env,
&input,
binding_kind,
match_mode,
patterns,
where_clause,
search,
)?
} else {
let source = RowSourceCtx {
clause,
binding_kind,
search,
};
if input.get_name(&search.binding_var).is_some() {
pre_bound_search_rows(&env, &input, &source)?
} else {
direct_search_rows(&env, &input, &source)?
}
};
matched =
filter_rows_where_clause(ctx.graph, ctx.params, search.post_where.as_ref(), matched)?;
let matched = if matched.is_empty() && optional {
vec![optional_null_row(
input,
patterns,
search.score_var.as_ref(),
)]
} else {
matched
};
for row in matched {
match fold {
Some(fold) => fold.offer(env.ctx.graph, row)?,
None => out.push(row),
}
}
}
Ok(out)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::exec::test_support::{
exec_autocommit, exec_cypher, named_node, profiled, try_exec_cypher,
};
use crate::graph::Graph;
use crate::metrics::KernelRung;
use relate_core::CapacityKind;
use relate_ir::{Direction, NodePattern, PatternElement, RelPattern};
fn rel(variable: &str) -> RelPattern {
RelPattern {
variable: Some(variable.into()),
types: Vec::new(),
type_expr: None,
direction: Direction::Outgoing,
properties: None,
prop_keys: Vec::new(),
var_length: false,
min_hops: 0,
max_hops: None,
where_clause: None,
quantified: false,
legacy_type_separator: false,
}
}
fn pattern(nodes: Vec<NodePattern>, rels: Vec<RelPattern>) -> PathPattern {
PathPattern {
variable: None,
subpath_variable: None,
elements: Vec::new(),
nodes,
rels,
where_clause: None,
mode: None,
selector: None,
is_shortest_path_function: false,
}
}
#[test]
fn binding_kind_reads_the_canonical_pattern_walk() {
let compact = pattern(vec![named_node("n")], vec![rel("r")]);
assert_eq!(
path_pattern_binding_kind(std::slice::from_ref(&compact), "n"),
Some(EntityKind::Node)
);
assert_eq!(
path_pattern_binding_kind(std::slice::from_ref(&compact), "r"),
Some(EntityKind::Relationship)
);
assert_eq!(
path_pattern_binding_kind(std::slice::from_ref(&compact), "p"),
None
);
let elements = PathPattern {
elements: vec![
PatternElement::Node(named_node("n")),
PatternElement::Relationship(rel("r")),
],
..pattern(Vec::new(), Vec::new())
};
assert_eq!(
path_pattern_binding_kind(&[elements], "r"),
Some(EntityKind::Relationship)
);
}
#[test]
fn check_binding_kind_separates_mismatch_from_unbound() {
assert!(check_binding_kind(Some(EntityKind::Node), EntityKind::Node).is_ok());
let mismatch =
check_binding_kind(Some(EntityKind::Relationship), EntityKind::Node).unwrap_err();
assert!(
mismatch.to_string().contains("does not match index"),
"{mismatch}"
);
let unbound = check_binding_kind(None, EntityKind::Node).unwrap_err();
assert!(
unbound
.to_string()
.contains("must be bound as a node or relationship"),
"{unbound}"
);
}
#[test]
fn attach_score_writes_only_a_named_score_column() {
let mut unnamed = Row::new();
attach_score(&mut unnamed, None, Value::Float(1.0));
assert!(unnamed.get("score").is_none());
let mut scored = Row::new();
attach_score(
&mut scored,
Some(&SmallName::from_name("score")),
Value::Float(1.0),
);
assert_eq!(scored.get("score"), Some(&Value::Float(1.0)));
let mut nulled = Row::new();
attach_score(
&mut nulled,
Some(&SmallName::from_name("score")),
Value::Null,
);
assert_eq!(nulled.get("score"), Some(&Value::Null));
}
fn vector_index_graph() -> Graph {
let g = Graph::default();
exec_autocommit(&g, "CREATE VECTOR INDEX vidx FOR (p:Person) ON p.embed").unwrap();
g.begin_write().unwrap();
for i in 0..8 {
g.create_node(
vec!["Person".into()],
BTreeMap::from([
("name".into(), Value::String(format!("p{i}").into())),
(
"embed".into(),
Value::List(vec![Value::Float(1.0), Value::Float(i as f64)].into()),
),
]),
)
.unwrap();
}
g.commit_write();
g
}
fn search_over_driving(driving: usize, tail: &str) -> String {
format!(
"UNWIND range(1, {driving}) AS i \
MATCH (p:Person) \
SEARCH p IN (VECTOR INDEX vidx FOR [1.0, 0.0] LIMIT 4) {tail}"
)
}
#[test]
fn a_search_match_feeding_a_fold_holds_no_rows() {
const DRIVING: usize = 30_000;
const CAP: u64 = 4 * 1024 * 1024;
let mut g = vector_index_graph();
g.configure_expression_memory_limit(Some(CAP));
let rows = exec_cypher(&g, &search_over_driving(DRIVING, "RETURN count(*) AS c")).rows;
assert_eq!(rows[0][0], Value::Int(4 * DRIVING as i64));
let error = try_exec_cypher(&g, &search_over_driving(DRIVING, "RETURN p.name AS name"))
.err()
.expect("the materializing form must be refused at the cap");
assert!(
matches!(
error,
Error::Capacity {
kind: CapacityKind::Expression,
..
}
),
"{error}"
);
}
#[test]
fn a_streamed_search_match_reports_the_walker_and_its_reads() {
let g = vector_index_graph();
let records = profiled(&g, &search_over_driving(3, "RETURN count(*) AS c"));
let record = records
.iter()
.find(|record| record.kernel.is_some())
.expect("the SEARCH MATCH records its rung");
assert_eq!(record.kernel, Some(KernelRung::Walker));
assert_eq!(record.reads.node_reads, 12, "{:?}", record.reads);
assert_eq!(record.rows, 12, "the rows the clause emitted into the fold");
assert_eq!(record.memory_bytes, 0, "a streamed clause holds nothing");
}
#[test]
fn a_pre_bound_limit_zero_window_answers_before_the_index_is_read() {
let g = vector_index_graph();
exec_autocommit(&g, "CREATE (:Person)-[:KNOWS]->(:Person)").unwrap();
let search = |limit: u32| {
format!(
"MATCH ()-[r:KNOWS]->() WITH r MATCH ()-[r]->() \
SEARCH r IN (VECTOR INDEX vidx FOR [1.0, 0.0] LIMIT {limit}) \
RETURN count(*) AS c"
)
};
let rejected = try_exec_cypher(&g, &search(1))
.err()
.expect("a LIMIT-1 window reads the index and rejects the kind mismatch");
assert!(
rejected.to_string().contains("does not match index"),
"{rejected}"
);
let rows = exec_cypher(&g, &search(0)).rows;
assert_eq!(rows[0][0], Value::Int(0));
}
#[test]
fn a_direct_limit_zero_window_answers_before_the_index_is_read() {
let g = vector_index_graph();
exec_autocommit(&g, "CREATE (:Person)-[:KNOWS]->(:Person)").unwrap();
let search = |limit: u32| {
format!(
"MATCH ()-[r:KNOWS]->() \
SEARCH r IN (VECTOR INDEX vidx FOR [1.0, 0.0] LIMIT {limit}) \
RETURN count(*) AS c"
)
};
let rejected = try_exec_cypher(&g, &search(1))
.err()
.expect("a LIMIT-1 window reads the index and rejects the kind mismatch");
assert!(
rejected.to_string().contains("does not match index"),
"{rejected}"
);
let rows = exec_cypher(&g, &search(0)).rows;
assert_eq!(rows[0][0], Value::Int(0));
}
}