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
24 changes: 15 additions & 9 deletions crates/lance-csr/src/csr_expand.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2099,15 +2099,15 @@ impl CsrExpandNode {
}

/// `plan`, a single hop that fetches its target, as a left outer expansion; `None`
/// for any other plan (a closing edge, a walk, a moved filter, a degree count).
/// for any other plan (a closing edge, a walk, a degree count). A filter already
/// moved into the hop must be the OPTIONAL MATCH's own WHERE: it then skips failing
/// neighbours, and a row with none left keeps its row of nulls.
pub(crate) fn outer_plan(plan: &LogicalPlan) -> Option<LogicalPlan> {
let LogicalPlan::Extension(ext) = plan else {
return None;
};
let node = ext.node.as_any().downcast_ref::<CsrExpandNode>()?;
let simple = node.target.is_some()
&& node.target_filter.is_none()
&& node.edge_filter.is_none()
&& node.closing_column.is_none()
&& node.traversal.is_none()
&& node.degrees.is_none();
Expand Down Expand Up @@ -2871,6 +2871,7 @@ async fn materialize(
target_filter: Option<&CompiledFilter>,
edge_filter: Option<&CompiledFilter>,
schema: &SchemaRef,
matched: Option<&mut [bool]>,
) -> datafusion::common::Result<RecordBatch> {
let mut expanded = expanded;
if let (Some(edge), Some(filter)) = (edge, edge_filter) {
Expand All @@ -2888,6 +2889,12 @@ async fn materialize(
}
_ => vec![],
};
// In an outer hop, a row counts as matched only once a neighbour passes the filters.
if let Some(matched) = matched {
for &row in &expanded.rows {
matched[row as usize] = true;
}
}
let ExpandedRows {
rows,
key_values,
Expand Down Expand Up @@ -3312,12 +3319,6 @@ impl ExecutionPlan for CsrExpandExec {
}
continue;
}
if let Some(matched) = expansion.matched.as_mut() {
// An outer node has no moved filter, so every chunk row is output.
for &row in &chunk.rows {
matched[row as usize] = true;
}
}
let batch = materialize(
&expansion.batch,
chunk,
Expand All @@ -3328,6 +3329,7 @@ impl ExecutionPlan for CsrExpandExec {
target_filter.as_deref(),
filter,
&schema,
expansion.matched.as_deref_mut(),
)
.await?;
if batch.num_rows() == 0 {
Expand Down Expand Up @@ -4323,6 +4325,7 @@ mod tests {
None,
None,
&out_schema,
None,
)
.await
.unwrap();
Expand Down Expand Up @@ -4762,6 +4765,7 @@ mod tests {
Some(&filter),
None,
&schema,
None,
)
.await
.unwrap();
Expand Down Expand Up @@ -4877,6 +4881,7 @@ mod tests {
None,
Some(&filter),
&schema,
None,
)
.await
.unwrap();
Expand All @@ -4900,6 +4905,7 @@ mod tests {
None,
None,
&schema,
None,
)
.await
.unwrap();
Expand Down
24 changes: 24 additions & 0 deletions crates/lance-csr/src/datafusion_planner/builder/join_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,11 @@ impl DataFusionPlanner {
optional: &LogicalOperator,
keys: &[String],
) -> Result<Option<LogicalPlan>> {
// The optional clause's own WHERE: kept in the hop below, if all of it moves there.
let (optional, predicate) = match optional {
LogicalOperator::Filter { input, predicate } => (input.as_ref(), Some(predicate)),
other => (other, None),
};
let LogicalOperator::Expand {
input: seed,
source_variable,
Expand Down Expand Up @@ -133,6 +138,25 @@ impl DataFusionPlanner {
properties,
target_properties,
)?;
let hop = match predicate {
None => hop,
// A neighbour that fails the filter is skipped, and a row left with none keeps
// one row of nulls: exactly a moved filter in an outer hop.
Some(predicate) => {
let expr = self.boolean_expr(predicate, hop.schema())?;
let filtered = LogicalPlanBuilder::from(hop)
.filter(expr)
.and_then(|b| b.build())
.map_err(|e| self.plan_error("Failed to build filter", e))?;
datafusion::optimizer::OptimizerRule::rewrite(
&crate::csr_expand::PushCsrTargetFilters,
filtered,
&datafusion::optimizer::OptimizerContext::new(),
)
.map_err(|e| self.plan_error("Failed to move the filter into the hop", e))?
.data
}
};
let outer = crate::csr_expand::CsrExpandNode::outer_plan(&hop);
if outer.is_none() {
ctx.relationship_instance_idx = saved;
Expand Down
2 changes: 1 addition & 1 deletion docs/csr.md
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ A hop runs on the CSR when **all three** conditions hold:
| `(a)-[:KNOWS*1..3]->(b)` | :material-check: single iterative expansion across the range |
| <code>(t:Tag)-[:hasType&#124;isSubclassOf*1..3]->(c:TagClass)</code> | :material-check: typed iterative expansion when all types and labels are indexed |
| <code>(a)-[:LIKES_POST&#124;LIKES_COMMENT]->(m)</code> | :material-check: one expansion per branch |
| `OPTIONAL MATCH (a)-[:KNOWS]->(b)` | :material-check: outer CSR expansion |
| `OPTIONAL MATCH (a)-[:KNOWS]->(b)`, with or without its own `WHERE` on `b` | :material-check: outer CSR expansion |
| `shortestPath((a)-[:KNOWS*]-(b))` | :material-check: BFS over the CSR adjacency |
| `WHERE NOT (b)-[:KNOWS]->(a)` | :material-check: in-place walk via [`PathExists`](internals/operators.md#pathexists-pattern-predicates-walked-in-place) |
| `(a)-[k:KNOWS]->(b)` | :material-check: edge properties fetched by row position (single hops) |
Expand Down
2 changes: 1 addition & 1 deletion docs/internals/operators.md
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ keeps the two hops from reusing one edge. Both plans start from `c` (Dan), not `
| Relationship filter: drops failing edges before anything else is fetched | `edge_filter=since > 2020` | `FilterExec` after the join |
| Closing edge: the target is already bound (a cycle), so only neighbours equal to it are kept. Each row reads the shorter of its two ends' lists (for a directed hop, the target's list is its incoming one), so a hub at one end costs no more than the other end's degree | `match=b__id` | Expanding everything, then filtering |
| [Iterative variable-length traversal](../csr.md#variable-length-traversal): one cursor per hop over typed (label, key) frontiers, with bounded output batches | `iterative hops=1..3` | One join branch per path length, combined with `UNION ALL` |
| Outer expansion for a one-hop `OPTIONAL MATCH` with no `WHERE` of its own: an input row with no neighbour keeps one row, with nulls in the columns the hop adds. No filter moves into an outer hop, because that would turn rows dropped by the filter into rows of nulls | `outer` | Planning the input a second time to start the optional side, then a left join back |
| Outer expansion for a one-hop `OPTIONAL MATCH`: an input row with no neighbour keeps one row, with nulls in the columns the hop adds. The optional clause's own `WHERE` moves into the hop when it reads only the optional node and relationship: a neighbour that fails it is skipped, and a row left with none keeps its row of nulls. No later filter moves in, because that would turn rows it drops into rows of nulls, and a `WHERE` that also reads earlier variables keeps the left join | `outer` | Planning the input a second time to start the optional side, then a left join back |
| Degrees: one row per input node with the number of its neighbours that pass the target filter, and how many of them are the node itself, for the [two-hop count](optimizer.md#two-hop-counts-from-degrees) | `degrees=[__n1, __s1]` | A hash aggregate over one row per edge |

A hop that uses several of these at once:
Expand Down
36 changes: 33 additions & 3 deletions python/python/tests/test_engine_optional.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,28 @@
"RETURN a.id, b.id",
[(1, 3), (2, 3), (3, 3), (4, N), (5, N), (6, N)],
),
# The optional clause's own WHERE on the relationship, on both, and with OR.
(
"MATCH (a:Person) OPTIONAL MATCH (a)-[r:KNOWS]->(b:Person) "
"WHERE r.since > 2002 RETURN a.id, b.id",
[(1, N), (2, 3), (3, 3), (4, N), (5, 1), (6, N)],
),
(
"MATCH (a:Person) OPTIONAL MATCH (a)-[r:KNOWS]->(b:Person) "
"WHERE r.since > 2002 AND b.age > 30 RETURN a.id, b.id",
[(1, N), (2, 3), (3, 3), (4, N), (5, N), (6, N)],
),
(
"MATCH (a:Person) OPTIONAL MATCH (a)-[:KNOWS]->(b:Person) "
"WHERE b.age < 25 OR b.age > 35 RETURN a.id, b.id",
[(1, 3), (2, 3), (3, 3), (4, N), (5, 1), (6, N)],
),
# A WHERE that also reads the earlier variable.
(
"MATCH (a:Person) OPTIONAL MATCH (a)-[:KNOWS]->(b:Person) WHERE b.age > a.age "
"RETURN a.id, b.id",
[(1, 2), (1, 2), (1, 3), (2, 3), (3, N), (4, N), (5, N), (6, N)],
),
(
"MATCH (a:Person) OPTIONAL MATCH (a)-[:KNOWS]->(b:Person) "
"RETURN a.id, count(b.id) AS n",
Expand Down Expand Up @@ -95,13 +117,21 @@ def test_optional_hop_is_one_outer_csr_expansion():
)
physical = plan[plan.index("physical_plan") :]
assert "outer" in physical and "Join" not in physical
# Its own WHERE keeps the CSR expansion on the optional side and the left join.
# Its own WHERE on the optional node or relationship moves into that expansion.
for where in ["b.age > 30", "r.since > 2002 AND b.age > 30"]:
plan = engine.explain(
"MATCH (a:Person) OPTIONAL MATCH (a)-[r:KNOWS]->(b:Person) "
f"WHERE {where} RETURN a.id, b.id"
)
physical = plan[plan.index("physical_plan") :]
assert "outer" in physical and "Join" not in physical, where
# A WHERE that reads an earlier variable can't: it keeps the left join.
plan = engine.explain(
"MATCH (a:Person) OPTIONAL MATCH (a)-[:KNOWS]->(b:Person) WHERE b.age > 30 "
"MATCH (a:Person) OPTIONAL MATCH (a)-[:KNOWS]->(b:Person) WHERE b.age > a.age "
"RETURN a.id, b.id"
)
physical = plan[plan.index("physical_plan") :]
assert "CsrExpandExec" in physical and "join_type=Left" in physical
assert "outer" not in physical and "join_type=Left" in physical


def test_optional_match_needs_a_bound_variable():
Expand Down
Loading