diff --git a/crates/lance-csr/src/logical_plan.rs b/crates/lance-csr/src/logical_plan.rs index b001102..a7ab27a 100644 --- a/crates/lance-csr/src/logical_plan.rs +++ b/crates/lance-csr/src/logical_plan.rs @@ -976,7 +976,8 @@ impl<'a> LogicalPlanner<'a> { } } GraphPattern::Path(path) if path.variable.is_some() || inventory_alternation => { - plan = Some(self.plan_inventory_path(plan, path)?) + let pruned = filter.and_then(|f| with_all_relationship_equalities(path, f)); + plan = Some(self.plan_inventory_path(plan, pruned.as_ref().unwrap_or(path))?) } GraphPattern::Path(path) if path.shortest.is_some() => { plan = Some(self.plan_shortest_path(plan, path)?) @@ -2379,6 +2380,121 @@ impl<'a> LogicalPlanner<'a> { } } +/// Copies `r.key = value` terms of `all(r IN relationships(p) WHERE ...)` conjuncts in +/// `filter` into the property map of every relationship of the named path `p`, so the +/// trail enumeration drops a failing edge as it reaches it instead of after building +/// the whole path. The WHERE still runs, so a term left out here only costs time. +/// Shortest paths are left alone: pruning edges would change which path is shortest. +fn with_all_relationship_equalities( + path: &PathPattern, + filter: &BooleanExpression, +) -> Option { + let variable = path + .variable + .as_deref() + .filter(|_| path.shortest.is_none())?; + let mut equalities = HashMap::new(); + for conjunct in conjuncts(filter) { + let BooleanExpression::Comparison { + left, + operator: ComparisonOperator::Equal, + right, + } = conjunct + else { + continue; + }; + // all(...) parses as a value compared with true. + let all = match (left, right) { + (all, ValueExpression::Literal(PropertyValue::Boolean(true))) + | (ValueExpression::Literal(PropertyValue::Boolean(true)), all) => all, + _ => continue, + }; + let ValueExpression::ListPredicate { + kind, + variable: element, + list, + predicate, + } = all + else { + continue; + }; + let over_path = matches!(list.as_ref(), ValueExpression::ScalarFunction { name, args } + if name.eq_ignore_ascii_case("relationships") + && matches!(args.as_slice(), [ValueExpression::Variable(p)] if p.eq_ignore_ascii_case(variable))); + let ValueExpression::Boolean(predicate) = predicate.as_ref() else { + continue; + }; + if kind != "all" || !over_path { + continue; + } + for term in conjuncts(predicate) { + let BooleanExpression::Comparison { + left, + operator: ComparisonOperator::Equal, + right, + } = term + else { + continue; + }; + let field = |value: &ValueExpression| match value { + ValueExpression::Field { base, field } if matches!(base.as_ref(), ValueExpression::LocalVariable(v) if v == element) => { + Some(field.clone()) + } + _ => None, + }; + let constant = |value: &ValueExpression| match value { + ValueExpression::Literal( + v @ (PropertyValue::String(_) + | PropertyValue::Integer(_) + | PropertyValue::Float(_) + | PropertyValue::Boolean(_) + | PropertyValue::Parameter(_)), + ) => Some(v.clone()), + ValueExpression::Parameter(name) => Some(PropertyValue::Parameter(name.clone())), + _ => None, + }; + if let Some((key, value)) = field(left) + .zip(constant(right)) + .or_else(|| field(right).zip(constant(left))) + { + equalities.entry(key).or_insert(value); + } + } + } + if equalities.is_empty() { + return None; + } + let mut path = path.clone(); + for segment in &mut path.segments { + for (key, value) in &equalities { + // An existing map entry already filters this key; the WHERE checks the rest. + if !segment + .relationship + .properties + .keys() + .any(|k| k.eq_ignore_ascii_case(key)) + { + segment + .relationship + .properties + .insert(key.clone(), value.clone()); + } + } + } + Some(path) +} + +fn conjuncts(expr: &BooleanExpression) -> Vec<&BooleanExpression> { + match expr { + BooleanExpression::And(a, b) => { + let mut all = conjuncts(a); + all.extend(conjuncts(b)); + all + } + other => vec![other], + } +} + #[cfg(test)] mod tests { use super::*; @@ -3321,6 +3437,69 @@ mod tests { ); } + /// The relationship property maps of the first PathMatch in a plan. + fn path_relationship_properties(query: &str) -> Vec> { + fn find(plan: &LogicalOperator) -> Option<&PathPattern> { + match plan { + LogicalOperator::PathMatch { path, .. } => Some(path), + LogicalOperator::Project { input, .. } | LogicalOperator::Filter { input, .. } => { + find(input) + } + _ => None, + } + } + let config = GraphConfig::builder() + .node_table("N", "id") + .rel_table("R", "N", "N", "src", "dst") + .build() + .unwrap(); + let plan = LogicalPlanner::new(&config) + .plan(&parse_cypher_query(query).unwrap()) + .unwrap(); + find(&plan) + .expect("a path match") + .segments + .iter() + .map(|s| s.relationship.properties.clone()) + .collect() + } + + #[test] + fn all_relationship_equalities_filter_each_path_edge() { + let maps = path_relationship_properties( + "MATCH p = (a:N {id: 0})-[:R*1..3]->(b:N)-[:R {day: 7}]->(c:N) \ + WHERE a.id = 0 AND all(r IN relationships(p) WHERE 5 = r.day AND r.kind = $k AND r.w > 1) \ + RETURN count(*)", + ); + assert_eq!(maps[0].get("day"), Some(&PropertyValue::Integer(5))); + assert_eq!( + maps[0].get("kind"), + Some(&PropertyValue::Parameter("k".into())) + ); + assert!(!maps[0].contains_key("w"), "only equalities are lowered"); + // An existing map entry stays; the WHERE still rejects the contradiction. + assert_eq!(maps[1].get("day"), Some(&PropertyValue::Integer(7))); + assert_eq!( + maps[1].get("kind"), + Some(&PropertyValue::Parameter("k".into())) + ); + } + + #[test] + fn other_path_predicates_leave_the_relationship_maps_alone() { + for predicate in [ + "any(r IN relationships(p) WHERE r.day = 5)", + "all(r IN relationships(p) WHERE r.day = 5) OR a.id = 1", + "NOT all(r IN relationships(p) WHERE r.day = 5)", + "all(r IN relationships(p) WHERE r.day = 5 OR r.day = 6)", + ] { + let maps = path_relationship_properties(&format!( + "MATCH p = (a:N)-[:R*1..3]->(b:N) WHERE {predicate} RETURN count(*)" + )); + assert!(maps[0].is_empty(), "{predicate}"); + } + } + #[test] fn continued_path_starts_from_the_bound_end_with_smaller_fan_out() { let config = GraphConfig::builder() diff --git a/crates/lance-csr/src/parser.rs b/crates/lance-csr/src/parser.rs index 51df444..fdf734d 100644 --- a/crates/lance-csr/src/parser.rs +++ b/crates/lance-csr/src/parser.rs @@ -692,21 +692,63 @@ fn where_clause(input: &str) -> IResult<&str, WhereClause> { let (input, _) = multispace0(input)?; let (input, _) = tag_no_case("WHERE")(input)?; let (input, _) = multispace1(input)?; - let (input, expression) = boolean_expression(input)?; + let (input, expression) = predicate(input)?; Ok((input, WhereClause { expression })) } +/// A condition of its own (`WHERE`, `WHEN`), where a bare value such as `n.active` also +/// counts. +fn predicate(input: &str) -> IResult<&str, BooleanExpression> { + alt((boolean_expression, bare_boolean))(input) +} + +/// A value used as a condition, read as `value = true` (as `all(...)` is), so null and +/// false both fail. +fn bare_boolean(input: &str) -> IResult<&str, BooleanExpression> { + let (input, _) = multispace0(input)?; + map(value_expression, |left| BooleanExpression::Comparison { + left, + operator: ComparisonOperator::Equal, + right: ValueExpression::Literal(PropertyValue::Boolean(true)), + })(input) +} + +/// An operand of AND, OR or NOT. A bare value qualifies after one of those keywords or +/// before AND/OR, but not alone, so `RETURN n.name` stays a value. +fn boolean_operand(after_keyword: bool) -> impl FnMut(&str) -> IResult<&str, BooleanExpression> { + move |input| { + if let Ok(parsed) = boolean_not_expression(input) { + return Ok(parsed); + } + let (rest, expr) = bare_boolean(input)?; + let before_keyword = tuple(( + multispace1, + alt((tag_no_case("AND"), tag_no_case("OR"))), + multispace1, + ))(rest) + .is_ok(); + if after_keyword || before_keyword { + Ok((rest, expr)) + } else { + Err(nom::Err::Error(nom::error::Error::new( + input, + nom::error::ErrorKind::Verify, + ))) + } + } +} + // Parse a boolean expression with OR precedence fn boolean_expression(input: &str) -> IResult<&str, BooleanExpression> { boolean_or_expression(input) } fn boolean_or_expression(input: &str) -> IResult<&str, BooleanExpression> { - let (input, first) = boolean_and_expression(input)?; + let (input, first) = boolean_and_expression(false)(input)?; let (input, rest) = many0(preceded( tuple((multispace0, tag_no_case("OR"), multispace1)), - boolean_and_expression, + boolean_and_expression(true), ))(input)?; let expr = rest.into_iter().fold(first, |acc, item| { BooleanExpression::Or(Box::new(acc), Box::new(item)) @@ -714,16 +756,20 @@ fn boolean_or_expression(input: &str) -> IResult<&str, BooleanExpression> { Ok((input, expr)) } -fn boolean_and_expression(input: &str) -> IResult<&str, BooleanExpression> { - let (input, first) = boolean_not_expression(input)?; - let (input, rest) = many0(preceded( - tuple((multispace0, tag_no_case("AND"), multispace1)), - boolean_not_expression, - ))(input)?; - let expr = rest.into_iter().fold(first, |acc, item| { - BooleanExpression::And(Box::new(acc), Box::new(item)) - }); - Ok((input, expr)) +fn boolean_and_expression( + after_keyword: bool, +) -> impl FnMut(&str) -> IResult<&str, BooleanExpression> { + move |input| { + let (input, first) = boolean_operand(after_keyword)(input)?; + let (input, rest) = many0(preceded( + tuple((multispace0, tag_no_case("AND"), multispace1)), + boolean_operand(true), + ))(input)?; + let expr = rest.into_iter().fold(first, |acc, item| { + BooleanExpression::And(Box::new(acc), Box::new(item)) + }); + Ok((input, expr)) + } } fn boolean_not_expression(input: &str) -> IResult<&str, BooleanExpression> { @@ -732,7 +778,7 @@ fn boolean_not_expression(input: &str) -> IResult<&str, BooleanExpression> { map( preceded( tuple((tag_no_case("NOT"), multispace1)), - boolean_not_expression, + boolean_operand(true), ), |expr| BooleanExpression::Not(Box::new(expr)), ), @@ -1216,7 +1262,7 @@ fn case_expression(input: &str) -> IResult<&str, ValueExpression> { let (input, operand) = opt(terminated(expression, peek(keyword("WHEN"))))(input)?; let (input, whens) = match &operand { None => many1(tuple(( - preceded(keyword("WHEN"), boolean_expression), + preceded(keyword("WHEN"), predicate), preceded(keyword("THEN"), expression), )))(input)?, Some(operand) => { @@ -2928,6 +2974,48 @@ mod tests { assert!(parse_cypher_query(&huge).is_err()); } + #[test] + fn bare_values_are_conditions() { + let is_true = |v: &str| BooleanExpression::Comparison { + left: ValueExpression::Property(PropertyRef::new("n", v)), + operator: ComparisonOperator::Equal, + right: ValueExpression::Literal(PropertyValue::Boolean(true)), + }; + let x_is_1 = BooleanExpression::Comparison { + left: ValueExpression::Property(PropertyRef::new("n", "x")), + operator: ComparisonOperator::Equal, + right: ValueExpression::Literal(PropertyValue::Integer(1)), + }; + let and = |a, b| BooleanExpression::And(Box::new(a), Box::new(b)); + let or = |a, b| BooleanExpression::Or(Box::new(a), Box::new(b)); + for (condition, expected) in [ + ("n.ok", is_true("ok")), + ("NOT n.ok", BooleanExpression::Not(Box::new(is_true("ok")))), + ("n.ok AND n.x = 1", and(is_true("ok"), x_is_1.clone())), + ("n.x = 1 AND n.ok", and(x_is_1.clone(), is_true("ok"))), + ("n.ok OR n.done", or(is_true("ok"), is_true("done"))), + ( + "n.x = 1 OR n.ok AND n.done", + or(x_is_1, and(is_true("ok"), is_true("done"))), + ), + ] { + let query = parse_cypher_query(&format!("MATCH (n:N) WHERE {condition} RETURN n")) + .unwrap_or_else(|e| panic!("{condition}: {e}")); + assert_eq!( + query.where_clause.unwrap().expression, + expected, + "{condition}" + ); + } + // A value on its own in a projection stays a value. + let query = parse_cypher_query("MATCH (n:N) RETURN n.name, n.x ORDER BY n.x").unwrap(); + assert!(query + .return_clause + .items + .iter() + .all(|item| matches!(item.expression, ValueExpression::Property(_)))); + } + #[test] fn relationship_type_alternation() { for q in [ diff --git a/docs/cypher.md b/docs/cypher.md index 87df4b1..f5039a7 100644 --- a/docs/cypher.md +++ b/docs/cypher.md @@ -371,6 +371,9 @@ RETURN length(p), nodes(p) expansion for the whole range; the join fallback uses one branch per length. A property map on a variable-length relationship, such as `[:KNOWS*1..3 {since: 2020}]`, must hold for every relationship on the path; a zero-hop match has none to check. Such a path uses the join fallback. + On a named path, `WHERE all(r IN relationships(p) WHERE r.since = 2020)` filters the same way: + equalities on `r` drop a failing relationship during the walk, and other conditions are checked + once each path is complete. - **Variable-length alternation** follows each relationship type's configured endpoint labels. With suitable CSR and node indexes, a mixed path such as `[:hasType|isSubclassOf*1..3]` stays in one operator. Named paths also support typed variable-length alternation through their edge inventory. @@ -461,7 +464,7 @@ This also applies inside `CALL` and `UNION`, and when equal-label endpoints pass | --- | --- | | Arithmetic | `+ - * / %` | | Comparison | `= <> != < <= > >=`, and chains such as `18 <= p.age < 65` | -| Boolean | `AND OR NOT` | +| Boolean | `AND OR NOT`; a boolean value is a condition on its own, as in `WHERE n.active` | | Strings | `STARTS WITH`, `ENDS WITH`, `CONTAINS`, and `LIKE` / `ILIKE` with SQL wildcards | | Lists | `IN`, literals `[1, 2]`, indexing `list[0]`, list comprehensions [x IN list WHERE ... | ...] | | Maps | Literals `{k: v}` and key access `m.k` | diff --git a/docs/internals/operators.md b/docs/internals/operators.md index 35489b9..d679d87 100644 --- a/docs/internals/operators.md +++ b/docs/internals/operators.md @@ -292,6 +292,8 @@ inventory of participating tables and tracks edge occurrences during traversal. Path property values are logical expressions, so cached plans bind them before physical planning. The physical operator then builds predicates against the inventory's node and relationship schemas. +The planner adds the equalities of a `WHERE all(r IN relationships(p) WHERE ...)` term to every +relationship's property map, so the walk skips failing edges; the `WHERE` itself still runs. Each execution starts with fresh inventory scans that can share source batches within that execution. ## `Apply`: correlated CALL subqueries diff --git a/python/python/tests/test_engine_expressions.py b/python/python/tests/test_engine_expressions.py index 513020c..0d3f873 100644 --- a/python/python/tests/test_engine_expressions.py +++ b/python/python/tests/test_engine_expressions.py @@ -9,7 +9,7 @@ import pyarrow as pa import pytest -from lance_csr import CypherEngine +from lance_csr import CypherEngine, GraphConfig from test_engine_csr import CONFIG, KNOWS, PEOPLE CASES = [ @@ -66,3 +66,34 @@ def test_coalesce_takes_the_first_non_null(): "MATCH (a:Person) RETURN a.id, coalesce(a.name, a.nick, 'none') AS n" ) assert rows(got) == [(1, "a"), (2, "bee"), (3, "none")] + + +@pytest.mark.parametrize( + ("query", "expected"), + [ + # Only true passes; false and null are dropped, as in openCypher. + ("MATCH (n:N) WHERE n.ok RETURN n.id AS id", [1, 4]), + ("MATCH (n:N) WHERE NOT n.ok RETURN n.id AS id", [2]), + ("MATCH (n:N) WHERE n.ok AND n.x = 1 RETURN n.id AS id", [1]), + ("MATCH (n:N) WHERE n.x = 2 OR n.ok RETURN n.id AS id", [1, 3, 4]), + ( + "MATCH (n:N) WITH collect(n) AS ns " + "RETURN 0 AS id, [m IN ns WHERE m.x = 1 AND m.ok | m.id] AS ids", + [(0, [1])], + ), + ( + "MATCH (n:N) RETURN n.id AS id, " + "CASE WHEN n.ok THEN 'yes' ELSE 'no' END AS answer", + [(1, "yes"), (2, "no"), (3, "no"), (4, "yes")], + ), + ], +) +def test_bare_boolean_values_are_conditions(query, expected): + config = GraphConfig.builder().node_table("N", "id").build() + nodes = pa.table( + {"id": [1, 2, 3, 4], "ok": [True, False, None, True], "x": [1, 1, 2, 3]} + ) + engine = CypherEngine(config, {"N": nodes}) + rows = engine.execute(query + " ORDER BY id").to_pylist() + values = [tuple(r.values()) if len(r) > 1 else r["id"] for r in rows] + assert values == expected diff --git a/python/python/tests/test_engine_paths.py b/python/python/tests/test_engine_paths.py index 6fca1f5..7b93782 100644 --- a/python/python/tests/test_engine_paths.py +++ b/python/python/tests/test_engine_paths.py @@ -192,3 +192,35 @@ def test_variable_length_property_map_filters_every_hop(use_csr, pattern, expect engine = CypherEngine(config, {"N": nodes, "R": rels}, use_csr=use_csr) result = engine.execute(f"MATCH {pattern} RETURN b.id AS b ORDER BY b") assert result.to_pydict() == {"b": expected} + + +@pytest.mark.parametrize("use_csr", [False, True]) +@pytest.mark.parametrize( + ("predicate", "expected"), + [ + # 2->3 has day 6, so the walk from 1 stops at 2. + ("all(r IN relationships(p) WHERE r.day = 5)", [2]), + ("all(r IN relationships(p) WHERE r.day = $day AND r.ok)", [2]), + ("all(r IN relationships(p) WHERE r.day = 6)", []), + # Not an equality, so it is checked after the walk. + ("all(r IN relationships(p) WHERE r.day >= 5)", [2, 3, 4]), + ("any(r IN relationships(p) WHERE r.day = 6)", [3, 4]), + ], +) +def test_all_relationships_predicate_filters_every_hop(use_csr, predicate, expected): + config = ( + GraphConfig.builder() + .node_table("N", "id") + .rel_table("R", "N", "N", "src", "dst") + .build() + ) + nodes = pa.table({"id": [1, 2, 3, 4]}) + rels = pa.table( + {"src": [1, 2, 3], "dst": [2, 3, 4], "day": [5, 6, 5], "ok": [True] * 3} + ) + engine = CypherEngine(config, {"N": nodes, "R": rels}, use_csr=use_csr) + query = ( + f"MATCH p = (a:N {{id: 1}})-[:R*1..3]->(b:N) WHERE {predicate} " + "RETURN b.id AS b ORDER BY b" + ) + assert engine.execute(query, {"day": 5}).to_pydict() == {"b": expected}