Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
181 changes: 180 additions & 1 deletion crates/lance-csr/src/logical_plan.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)?)
Expand Down Expand Up @@ -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<PathPattern> {
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::*;
Expand Down Expand Up @@ -3321,6 +3437,69 @@ mod tests {
);
}

/// The relationship property maps of the first PathMatch in a plan.
fn path_relationship_properties(query: &str) -> Vec<HashMap<String, PropertyValue>> {
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()
Expand Down
118 changes: 103 additions & 15 deletions crates/lance-csr/src/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -692,38 +692,84 @@ 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))
});
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> {
Expand All @@ -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)),
),
Expand Down Expand Up @@ -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) => {
Expand Down Expand Up @@ -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 [
Expand Down
5 changes: 4 additions & 1 deletion docs/cypher.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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 <code>[x IN list WHERE ... &#124; ...]</code> |
| Maps | Literals `{k: v}` and key access `m.k` |
Expand Down
2 changes: 2 additions & 0 deletions docs/internals/operators.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading
Loading