diff --git a/crates/lance-csr-node/src/engine.rs b/crates/lance-csr-node/src/engine.rs index 50a7883..4698aea 100644 --- a/crates/lance-csr-node/src/engine.rs +++ b/crates/lance-csr-node/src/engine.rs @@ -76,6 +76,28 @@ pub struct GraphExport { pub dropped_edges: i64, } +impl From for GraphExport { + fn from(g: lance_csr::GraphExport) -> Self { + Self { + num_nodes: g.num_nodes as i64, + directed: g.directed, + node_keys: into_vec(g.node_keys).into(), + label_ranges: g + .label_ranges + .into_iter() + .map(|(label, start, end)| (label, vec![start as i64, end as i64])) + .collect(), + out_indptr: into_vec(g.out_indptr).into(), + out_indices: into_vec(g.out_indices).into(), + in_indptr: g.in_indptr.map(|a| into_vec(a).into()), + in_indices: g.in_indices.map(|a| into_vec(a).into()), + out_weights: g.out_weights.map(|a| into_vec(a).into()), + in_weights: g.in_weights.map(|a| into_vec(a).into()), + dropped_edges: g.dropped_edges as i64, + } + } +} + /// The array's values as a `Vec`, without copying when the buffer is uniquely owned. fn into_vec( array: arrow_array::PrimitiveArray, @@ -303,23 +325,41 @@ impl CypherEngine { .await }) .await?; - Ok(GraphExport { - num_nodes: g.num_nodes as i64, - directed: g.directed, - node_keys: into_vec(g.node_keys).into(), - label_ranges: g - .label_ranges - .into_iter() - .map(|(label, start, end)| (label, vec![start as i64, end as i64])) - .collect(), - out_indptr: into_vec(g.out_indptr).into(), - out_indices: into_vec(g.out_indices).into(), - in_indptr: g.in_indptr.map(|a| into_vec(a).into()), - in_indices: g.in_indices.map(|a| into_vec(a).into()), - out_weights: g.out_weights.map(|a| into_vec(a).into()), - in_weights: g.in_weights.map(|a| into_vec(a).into()), - dropped_edges: g.dropped_edges as i64, + Ok(g.into()) + } + + #[napi] + pub async fn export_subgraph( + &self, + query: String, + params_json: Option, + directed: bool, + weight: Option, + combine_edges: Option, + default_weight: Option, + ) -> napi::Result { + let combine = combine_edges + .as_deref() + .map(str::parse::) + .transpose() + .map_err(graph_error)? + .unwrap_or_default(); + let weights = + (weight.is_some() || default_weight.is_some()).then(|| lance_csr::EdgeWeights { + column: weight, + default: default_weight, + combine, + ..Default::default() + }); + let params = params(params_json)?; + let inner = self.inner.clone(); + let g = blocking(async move { + inner + .export_subgraph(&query, params, directed, weights.as_ref()) + .await }) + .await?; + Ok(g.into()) } #[napi] diff --git a/crates/lance-csr-python/src/graph.rs b/crates/lance-csr-python/src/graph.rs index d7a3434..d530aa7 100644 --- a/crates/lance-csr-python/src/graph.rs +++ b/crates/lance-csr-python/src/graph.rs @@ -1388,6 +1388,40 @@ impl CypherEngine { Ok(GraphExport { inner }) } + #[pyo3(signature = ( + query, params=None, *, directed=true, weight=None, combine_edges="sum", default_weight=None + ))] + #[allow(clippy::too_many_arguments)] + fn export_subgraph( + &self, + py: Python, + query: &str, + params: Option<&Bound<'_, PyDict>>, + directed: bool, + weight: Option, + combine_edges: &str, + default_weight: Option, + ) -> PyResult { + let combine = combine_edges + .parse::() + .map_err(graph_error_to_pyerr)?; + let weights = (weight.is_some() || default_weight.is_some()).then(|| lance_csr::EdgeWeights { + column: weight, + default: default_weight, + combine, + ..Default::default() + }); + let params = python_params(params)?; + let inner = RT + .block_on( + Some(py), + self.inner + .export_subgraph(query, params, directed, weights.as_ref()), + )? + .map_err(graph_error_to_pyerr)?; + Ok(GraphExport { inner }) + } + #[pyo3(signature = (export, column, values, *, overwrite=false))] fn write_node_column( &self, diff --git a/crates/lance-csr/src/engine.rs b/crates/lance-csr/src/engine.rs index bc8b07d..5854214 100644 --- a/crates/lance-csr/src/engine.rs +++ b/crates/lance-csr/src/engine.rs @@ -1618,8 +1618,9 @@ impl CypherEngine { /// # Errors /// [`GraphError::ConfigError`] for an unknown relationship type or label, a missing /// or non-integer key or endpoint column, a missing or non-numeric weight column, a type - /// with no weight column and no default, or nothing to export; [`GraphError::ExecutionError`] for a repeated node key or a - /// failed scan. An edge with a null weight is dropped and counted in `dropped_edges`. + /// with no weight column and no default, or nothing to export; + /// [`GraphError::ExecutionError`] for a repeated node key or a failed scan. An edge with a + /// null weight is dropped and counted in `dropped_edges`. pub async fn export_graph( &self, rel_types: Option<&[String]>, @@ -1637,6 +1638,37 @@ impl CypherEngine { .await } + /// The part of the graph a Cypher query selects, as dense CSR arrays: the same form and + /// edge rules as [`CypherEngine::export_graph`]. + /// + /// The query's first two RETURN columns are the source and target node keys, one row per + /// edge. The nodes are the keys present. When both columns are a labeled node's key + /// (`RETURN a.id, b.id` with `(a:Person)`, and `id` its key), ids are grouped per label as + /// in `export_graph`, so `label_ranges` is filled and [`CypherEngine::write_node_column`] + /// works; otherwise all keys share one id space and `label_ranges` is empty. `weights` + /// names a column of the result (not one per relationship type), or sets one weight per + /// row with `default`. + /// + /// # Errors + /// Any error of [`CypherEngine::execute`]; [`GraphError::ConfigError`] when the first two + /// columns aren't integer keys, the weight column is missing or isn't numeric, or weights + /// are given per relationship type. + pub async fn export_subgraph( + &self, + query: &str, + params: HashMap, + directed: bool, + weights: Option<&crate::graph_export::EdgeWeights>, + ) -> Result { + let state = self.snapshot(); + let parsed = self.parse(query, params, &state, true)?; + let labels = crate::graph_export::returned_labels(&self.config, parsed.ast()); + let rows = parsed + .execute_with_catalog_and_context(state.catalog.clone(), state.context.clone()) + .await?; + crate::graph_export::export_rows(&rows, labels, directed, weights) + } + /// Add `column` to the node tables of `export`, from `values` indexed by dense id, and pin the /// engine to the new versions of those datasets. /// diff --git a/crates/lance-csr/src/graph_export.rs b/crates/lance-csr/src/graph_export.rs index 01619c3..49aeabe 100644 --- a/crates/lance-csr/src/graph_export.rs +++ b/crates/lance-csr/src/graph_export.rs @@ -320,22 +320,13 @@ pub(crate) async fn export_graph( ))); } - // Edges as packed `row * n + column` keys, both orientations at once. - // Sized from row counts (Lance metadata): growing by doubling would peak at - // several times the final size while copying. + // Row counts (Lance metadata) size the edge vectors. let mut rows = 0; for rel in &rels { rows += rel.source.num_rows(&rel.name).await?; } - // Exactly one of the key and the (key, weight) vectors is used. - let weighted = weights.is_some(); - let (keys_cap, pairs_cap) = if weighted { (0, rows) } else { (rows, 0) }; - // Out-edges only: directed in-edges come from transposing the out CSR, and undirected - // reverse edges go into the same vector. - let mut out: Vec = Vec::with_capacity(if directed { keys_cap } else { 2 * keys_cap }); - let mut out_w: Vec<(u64, f64)> = - Vec::with_capacity(if directed { pairs_cap } else { 2 * pairs_cap }); - let mut dropped = 0u64; + let combine = weights.map(|w| w.combine).unwrap_or_default(); + let mut edges = EdgeBuilder::new(n, directed, weights.is_some(), rows); for rel in &rels { let (src_map, dst_map) = (&maps[rel.src_label], &maps[rel.dst_label]); let mut columns = vec![rel.src.as_str(), rel.dst.as_str()]; @@ -354,75 +345,325 @@ pub(crate) async fn export_graph( Some(name) => Some(float64(batch.column(2), name, &rel.name)?), None => None, }; - let pairs: Vec> = (0..batch.num_rows()) - .into_par_iter() - .with_min_len(4096) - .filter(|&i| s.is_valid(i) && d.is_valid(i)) - .map(|i| { - // A null weight drops the edge, as a missing endpoint does: no weight - // is a safe stand-in for an unknown one. - if w.as_ref().is_some_and(|w| w.is_null(i)) { - return None; - } - Some((*src_map.get(&s.value(i))?, *dst_map.get(&d.value(i))?, i)) - }) - .collect(); - for pair in pairs { - let Some((a, b, i)) = pair else { - dropped += 1; - continue; - }; - // A self-loop's reverse is itself; adding it would count its weight twice. - let reverse = !directed && a != b; - if weighted { - let w = w.as_ref().map_or(constant, |w| w.value(i)); - out_w.push((a * n + b, w)); - if reverse { - out_w.push((b * n + a, w)); - } - } else { - out.push(a * n + b); - if reverse { - out.push(b * n + a); - } + edges.add(&s, &d, src_map, dst_map, w.as_ref(), constant); + } + } + Ok(edges.finish(Int64Array::from(node_keys), label_ranges, combine)) +} + +/// The node label of each of a query's first two RETURN columns, when both are a node's key. +/// +/// `a.id` resolves to `Person` when the MATCH binds `a` to the single label `Person` and `id` +/// is that label's key column. Anything else (an unlabeled or multi-label node, a computed +/// expression, a WITH stage or UNION that may rebind variables) gives `None`: the keys are +/// then one key space without labels. +pub(crate) fn returned_labels( + config: &GraphConfig, + query: &crate::ast::CypherQuery, +) -> Option<[String; 2]> { + use crate::ast::{GraphPattern, NodePattern, ReadingClause, ValueExpression}; + if query.with_clause.is_some() + || !query.further_with_stages.is_empty() + || !query.union_branches.is_empty() + { + return None; + } + let mut labels: HashMap> = HashMap::new(); + let mut note = |node: &NodePattern| { + if let Some(variable) = &node.variable { + labels + .entry(variable.clone()) + .or_default() + .extend(node.labels.iter().cloned()); + } + }; + for clause in &query.reading_clauses { + let ReadingClause::Match(m) = clause else { + continue; + }; + for pattern in &m.patterns { + match pattern { + GraphPattern::Node(node) => note(node), + GraphPattern::Path(path) => { + note(&path.start_node); + path.segments.iter().for_each(|s| note(&s.end_node)); } } } } + let resolve = |i: usize| -> Option { + let ValueExpression::Property(p) = &query.return_clause.items.get(i)?.expression else { + return None; + }; + let mut names = labels.get(&p.variable)?.clone(); + names.sort_by_key(|l| l.to_lowercase()); + names.dedup_by(|a, b| a.eq_ignore_ascii_case(b)); + let [label] = names.as_slice() else { + return None; + }; + let mapping = config.get_node_mapping(label)?; + mapping + .id_field + .eq_ignore_ascii_case(&p.property) + .then(|| mapping.label.clone()) + }; + Some([resolve(0)?, resolve(1)?]) +} + +/// Build an export from a query result whose first two columns are the source and target +/// keys. With `labels`, each column's keys are that label's nodes and ids are grouped per +/// label as in [`export_graph`]; without, all keys share one id space. +pub(crate) fn export_rows( + rows: &arrow::array::RecordBatch, + labels: Option<[String; 2]>, + directed: bool, + weights: Option<&EdgeWeights>, +) -> Result { + const TABLE: &str = "the query result"; + let schema = rows.schema(); + if schema.fields().len() < 2 { + return Err(config_error( + "The query must return the source and target keys as its first two columns".to_string(), + )); + } + let mut ends = Vec::with_capacity(2); + for field in &schema.fields()[..2] { + if !is_supported_id_type(field.data_type()) { + return Err(config_error(format!( + "Column '{}' of {TABLE} is {}, not an integer key type the export supports", + field.name(), + field.data_type() + ))); + } + ends.push(int64(rows.column(ends.len()), field.name(), TABLE)?); + } + let (s, d) = (&ends[0], &ends[1]); + let (weight, constant) = match weights { + None => (None, 0.0), + Some(w) if !w.per_type.is_empty() => { + return Err(config_error( + "A subgraph's weights come from a column of the query result: name one, not \ + one per relationship type" + .to_string(), + )) + } + Some(EdgeWeights { + column: Some(name), .. + }) => { + let (i, field) = schema + .fields() + .iter() + .enumerate() + .find(|(_, f)| f.name().eq_ignore_ascii_case(name)) + .ok_or_else(|| { + config_error(format!("Weight column '{name}' not found in {TABLE}")) + })?; + if !field.data_type().is_numeric() { + return Err(config_error(format!( + "Weight column '{name}' of {TABLE} is {}, not a numeric type", + field.data_type() + ))); + } + (Some(float64(rows.column(i), name, TABLE)?), 0.0) + } + Some(EdgeWeights { + default: Some(value), + .. + }) => (None, *value), + Some(_) => { + return Err(config_error( + "Edge weights need a weight column or a default weight".to_string(), + )) + } + }; - let (out_indptr, out_indices, out_weights) = if weighted { - drop(out); - let combine = weights.map(|w| w.combine).unwrap_or_default(); - let (p, i, w) = weighted_csr(n, out_w, combine); - (p, i, Some(w)) - } else { - drop(out_w); - let (p, i) = csr(n, out); - (p, i, None) + // Each id space's keys: the endpoints present, sorted. One space per label (in label + // name order, as in `export_graph`), or one for all keys. + let valid = |i: &usize| s.is_valid(*i) && d.is_valid(*i); + let column_keys = |column: &Int64Array| -> Vec { + (0..rows.num_rows()) + .filter(valid) + .map(|i| column.value(i)) + .collect() }; - let (in_indptr, in_indices, in_weights) = if directed { - let (p, i, w) = transpose( - out_indptr.values(), - out_indices.values(), - out_weights.as_ref().map(|w| w.values().as_ref()), - ); - (Some(p), Some(i), w) - } else { - (None, None, None) + let mut spaces: Vec<(Option, Vec)> = match &labels { + Some([a, b]) if a == b => { + let mut keys = column_keys(s); + keys.extend(column_keys(d)); + vec![(Some(a.clone()), keys)] + } + Some([a, b]) => { + let mut spaces = vec![ + (Some(a.clone()), column_keys(s)), + (Some(b.clone()), column_keys(d)), + ]; + spaces.sort_by(|x, y| x.0.cmp(&y.0)); + spaces + } + None => { + let mut keys = column_keys(s); + keys.extend(column_keys(d)); + vec![(None, keys)] + } + }; + let mut node_keys = Vec::new(); + let mut label_ranges = Vec::new(); + let mut maps = Vec::with_capacity(spaces.len()); + for (label, keys) in &mut spaces { + keys.par_sort_unstable(); + keys.dedup(); + let start = node_keys.len() as u64; + let mut map = FastMap::with_capacity_and_hasher(keys.len(), RandomState::default()); + for &key in keys.iter() { + map.insert(key, node_keys.len() as u64); + node_keys.push(key); + } + if let Some(label) = label { + label_ranges.push((label.clone(), start, node_keys.len() as u64)); + } + maps.push(map); + } + drop(spaces); + let n = node_keys.len() as u64; + if n > u64::from(u32::MAX) { + // `row * n + column` must fit in a u64. + return Err(exec_error(format!( + "{n} nodes is more than the export supports" + ))); + } + // The source column's map comes first unless the labels are ordered the other way. + let (src_map, dst_map) = match (&labels, maps.as_slice()) { + (Some([a, b]), [first, second]) if a > b => (second, first), + (_, [first, second]) => (first, second), + (_, [only]) => (only, only), + _ => unreachable!("one or two id spaces"), }; - Ok(GraphExport { - num_nodes: n, - directed, - node_keys: Int64Array::from(node_keys), - label_ranges, - out_indptr, - out_indices, - in_indptr, - in_indices, - out_weights, - in_weights, - dropped_edges: dropped, - }) + let mut builder = EdgeBuilder::new(n, directed, weights.is_some(), rows.num_rows()); + builder.add(s, d, src_map, dst_map, weight.as_ref(), constant); + let combine = weights.map(|w| w.combine).unwrap_or_default(); + Ok(builder.finish(Int64Array::from(node_keys), label_ranges, combine)) +} + +/// Edges mapped to dense ids, collected for the CSR build. +/// +/// Out-edges only: a directed graph's in-edges come from transposing the out CSR, and an +/// undirected graph's reverse edges go into the same vector. Exactly one of the packed-key +/// and the `(key, weight)` vectors is used, so an unweighted build allocates nothing for +/// weights. +struct EdgeBuilder { + n: u64, + directed: bool, + weighted: bool, + out: Vec, + out_w: Vec<(u64, f64)>, + dropped: u64, +} + +impl EdgeBuilder { + /// `rows` sizes the vectors up front: growing by doubling would peak at several times + /// the final size while copying. + fn new(n: u64, directed: bool, weighted: bool, rows: usize) -> Self { + let rows = if directed { rows } else { 2 * rows }; + let (keys, pairs) = if weighted { (0, rows) } else { (rows, 0) }; + Self { + n, + directed, + weighted, + out: Vec::with_capacity(keys), + out_w: Vec::with_capacity(pairs), + dropped: 0, + } + } + + /// Add one batch of edges. A null endpoint skips the edge; an endpoint key missing from + /// its map, or a null weight, drops it and counts it. Without a weight column, a weighted + /// build gives every edge `constant`. + fn add( + &mut self, + s: &Int64Array, + d: &Int64Array, + src_map: &FastMap, + dst_map: &FastMap, + w: Option<&Float64Array>, + constant: f64, + ) { + let pairs: Vec> = (0..s.len()) + .into_par_iter() + .with_min_len(4096) + .filter(|&i| s.is_valid(i) && d.is_valid(i)) + .map(|i| { + // A null weight drops the edge, as a missing endpoint does: no weight + // is a safe stand-in for an unknown one. + if w.is_some_and(|w| w.is_null(i)) { + return None; + } + Some((*src_map.get(&s.value(i))?, *dst_map.get(&d.value(i))?, i)) + }) + .collect(); + let n = self.n; + for pair in pairs { + let Some((a, b, i)) = pair else { + self.dropped += 1; + continue; + }; + // A self-loop's reverse is itself; adding it would count its weight twice. + let reverse = !self.directed && a != b; + if self.weighted { + let w = w.map_or(constant, |w| w.value(i)); + self.out_w.push((a * n + b, w)); + if reverse { + self.out_w.push((b * n + a, w)); + } + } else { + self.out.push(a * n + b); + if reverse { + self.out.push(b * n + a); + } + } + } + } + + /// Sort, deduplicate (combining weights by `combine`) and build the CSR arrays. + fn finish( + self, + node_keys: Int64Array, + label_ranges: Vec<(String, u64, u64)>, + combine: CombineEdges, + ) -> GraphExport { + let (n, directed) = (self.n, self.directed); + let (out_indptr, out_indices, out_weights) = if self.weighted { + drop(self.out); + let (p, i, w) = weighted_csr(n, self.out_w, combine); + (p, i, Some(w)) + } else { + drop(self.out_w); + let (p, i) = csr(n, self.out); + (p, i, None) + }; + let (in_indptr, in_indices, in_weights) = if directed { + let (p, i, w) = transpose( + out_indptr.values(), + out_indices.values(), + out_weights.as_ref().map(|w| w.values().as_ref()), + ); + (Some(p), Some(i), w) + } else { + (None, None, None) + }; + GraphExport { + num_nodes: n, + directed, + node_keys, + label_ranges, + out_indptr, + out_indices, + in_indptr, + in_indices, + out_weights, + in_weights, + dropped_edges: self.dropped, + } + } } /// CSR offsets, `n + 1` entries, from each entry's row in order. @@ -535,6 +776,14 @@ pub(crate) async fn write_node_column( ))); } + if export.label_ranges.is_empty() { + return Err(config_error( + "This export has no node labels (its query's keys couldn't be matched to labels), \ + so there is no node table to write to; join its node_keys to your table instead" + .to_string(), + )); + } + // Check every label first: a Lance dataset, and a column name that isn't its key. let mut targets = Vec::with_capacity(export.label_ranges.len()); for (label, start, end) in &export.label_ranges { @@ -1084,6 +1333,140 @@ mod tests { assert!(g.is_err(), "KNOWS isn't exported"); } + #[tokio::test] + async fn subgraph_of_a_query_by_the_export_rules() { + let (nodes, edges) = weighted_people(powers_of_two()); + let engine = arrow_engine(person_config(), vec![("Person", nodes), ("KNOWS", edges)]).await; + let sub = |q: &str, directed: bool, w: Option| { + let engine = &engine; + let q = q.to_string(); + async move { + engine + .export_subgraph(&q, HashMap::new(), directed, w.as_ref()) + .await + } + }; + let all = "MATCH (a:Person)-[:KNOWS]->(b:Person) RETURN a.id, b.id"; + + // The query's join drops 10->99 and the null endpoint; the nodes are the keys present, + // sorted: 10, 20, 30, 50, 60. The isolated 40 isn't in the subgraph. + let g = sub(all, true, None).await.unwrap(); + assert_eq!(g.node_keys.values().to_vec(), vec![10, 20, 30, 50, 60]); + assert_eq!(g.label_ranges, vec![("Person".to_string(), 0, 5)]); + assert_eq!(values(&g.out_indptr), vec![0, 1, 2, 4, 5, 6]); + assert_eq!(values(&g.out_indices), vec![1, 2, 0, 2, 4, 3]); + assert_eq!( + values(g.in_indices.as_ref().unwrap()), + vec![2, 0, 1, 2, 4, 3] + ); + assert_eq!(g.dropped_edges, 0); + + // A filter selects the subgraph. + let g = sub( + "MATCH (a:Person)-[:KNOWS]->(b:Person) WHERE a.id >= 30 RETURN a.id, b.id", + false, + None, + ) + .await + .unwrap(); + assert_eq!(g.node_keys.values().to_vec(), vec![10, 30, 50, 60]); + assert_eq!(values(&g.out_indptr), vec![0, 1, 3, 4, 5]); + assert_eq!(values(&g.out_indices), vec![1, 0, 1, 3, 2]); + + // A weight column of the result: the duplicate 10->20 sums 1 and 2. + let g = sub( + "MATCH (a:Person)-[r:KNOWS]->(b:Person) RETURN a.id, b.id, r.w AS cost", + true, + Some(EdgeWeights::column("COST")), + ) + .await + .unwrap(); + assert_eq!( + weights(&g.out_weights), + vec![3.0, 4.0, 8.0, 16.0, 64.0, 128.0] + ); + // One weight per row counts the rows behind each edge. + let g = sub( + all, + true, + Some(EdgeWeights { + default: Some(1.0), + ..EdgeWeights::default() + }), + ) + .await + .unwrap(); + assert_eq!(weights(&g.out_weights), vec![2.0, 1.0, 1.0, 1.0, 1.0, 1.0]); + + // Keys that aren't a labeled node's key: one id space, no labels. + let g = sub( + "MATCH (a:Person)-[:KNOWS]->(b) RETURN a.id, b.id", + true, + None, + ) + .await + .unwrap(); + assert!(g.label_ranges.is_empty()); + assert_eq!(g.node_keys.values().to_vec(), vec![10, 20, 30, 50, 60]); + + // Errors: a non-integer key column, weights per relationship type, a missing column. + for (q, w) in [ + ( + "MATCH (a:Person)-[:KNOWS]->(b:Person) RETURN 'x' AS s, b.id", + None, + ), + ( + all, + Some(EdgeWeights { + per_type: vec![("KNOWS".to_string(), "w".to_string())], + ..EdgeWeights::default() + }), + ), + (all, Some(EdgeWeights::column("cost"))), + ("MATCH (a:Person) RETURN a.id", None), + ] { + let err = sub(q, true, w).await.unwrap_err(); + assert!(matches!(err, GraphError::ConfigError { .. }), "{q}: {err}"); + } + } + + #[tokio::test] + async fn subgraph_labels_keep_colliding_keys_apart() { + let config = GraphConfig::builder() + .node_table("Person", "id") + .node_table("City", "id") + .rel_table("LIVES_IN", "Person", "City", "src", "dst") + .build() + .unwrap(); + let ids = || batch(&[("id", vec![Some(1), Some(2), Some(3)])]); + let lives_in = batch(&[ + ("src", vec![Some(1), Some(2), Some(3)]), + ("dst", vec![Some(2), Some(1), Some(2)]), + ]); + let engine = arrow_engine( + config, + vec![("Person", ids()), ("City", ids()), ("LIVES_IN", lives_in)], + ) + .await; + let g = engine + .export_subgraph( + "MATCH (p:Person)-[:LIVES_IN]->(c:City) WHERE p.id <= 2 RETURN p.id, c.id", + HashMap::new(), + true, + None, + ) + .await + .unwrap(); + // City 1, 2 then Person 1, 2: equal keys, distinct nodes. + assert_eq!( + g.label_ranges, + vec![("City".to_string(), 0, 2), ("Person".to_string(), 2, 4)] + ); + assert_eq!(g.node_keys.values().to_vec(), vec![1, 2, 1, 2]); + assert_eq!(values(&g.out_indptr), vec![0, 0, 0, 1, 2]); + assert_eq!(values(&g.out_indices), vec![1, 0]); + } + #[tokio::test] async fn bad_weight_columns_are_errors() { let (nodes, edges) = weighted_people(powers_of_two()); diff --git a/docs/graph-algorithms.md b/docs/graph-algorithms.md index 9875e3b..60d9498 100644 --- a/docs/graph-algorithms.md +++ b/docs/graph-algorithms.md @@ -19,6 +19,9 @@ copying. Every parameter is optional, and all but `rel_types` are keyword-only: | `combine_edges` | `"sum"` | How an edge listed more than once combines its weights: `"sum"`, `"min"` or `"max"`. See [Weighted graphs](#weighted-graphs). | | `default_weight` | `None` | The weight of every edge of a type with no weight column; `None` makes such a type an error. See [Several relationship types](#several-relationship-types). | +To export only the part of the graph a Cypher query selects, use `export_subgraph`, described in +[Subgraphs](#subgraphs). + ## What the export contains A CSR numbers the nodes `0` to `n - 1`, its *dense ids*, and stores the edges in two arrays: @@ -183,6 +186,58 @@ become one edge with one combined weight. A self-loop's weight counts once. Weights cost memory only when you ask for them. Without `weight`, the export reads no extra column and `out_weights` and `in_weights` are `None`. +## Subgraphs + +An analysis often needs only part of the graph: the busiest accounts and their contacts, or one region's roads. +Ranking the whole graph and filtering the scores afterwards gives a different answer, since PageRank on a +subgraph only counts the edges inside it. [`export_subgraph`][lance_csr.CypherEngine.export_subgraph] runs a +Cypher query that selects the edges, and builds the same arrays as `export_graph` from its result: + +```python +sub = engine.export_subgraph( + "MATCH (a:Person)-[:FOLLOWS]->(b:Person) WHERE a.id = $who RETURN a.id, b.id", + {"who": 10}, +) +print(sub.node_keys.to_pylist()) # [10, 20, 30] +print(sub.out_indptr.to_pylist(), sub.out_indices.to_pylist()) # [0, 2, 2, 2] [1, 2] +print(sub.label_ranges) # {'Person': (0, 3)} +``` + +The query returns one row per edge, with the source and target node keys as its first two columns. The nodes are +the keys present in the result, sorted, so Dan (40) and anyone else outside the selected edges aren't in the +export. The edges follow the same rules as `export_graph`: an edge listed twice appears once, `directed=False` +lists each edge both ways, and a self-loop counts once. + +When both key columns are a labeled node's key, as `a.id` here with `a` a `Person` and `id` its key, the export +groups the ids per label as `export_graph` does. `label_ranges` is filled, and +[`write_node_column`](#writing-results-back-to-lance) can write an algorithm's results back to the node table, with +nulls for the nodes outside the subgraph. When a column is computed, or its node has no single label, all keys +share one id space and `label_ranges` is empty; join `node_keys` to your own table instead. + +The options are those of `export_graph`, except that the query does the selecting, so there is no `rel_types`, +and `weight` names a column of the query result: + +| Parameter | Default | What it controls | +| --- | --- | --- | +| `query`, `params` | | The Cypher query and its parameters, as for [`execute`][lance_csr.CypherEngine.execute]. | +| `directed` | `True` | `True` returns out-edge and in-edge arrays; `False` returns one set listing every edge both ways. | +| `weight` | `None` | A numeric column of the result, such as `r.cost AS cost`, exported as `float64` edge weights. | +| `combine_edges` | `"sum"` | How an edge listed more than once combines its weights: `"sum"`, `"min"` or `"max"`. | +| `default_weight` | `None` | Without `weight`, the weight of every row. | + +`default_weight=1.0` without `weight` gives each edge the number of rows that list it. That turns a result with +repeated rows into a graph where repeated edges count more, as PageRank on a multigraph does: + +```python +counted = weighted_engine.export_subgraph( + "MATCH (a:Person)-[:FOLLOWS]->(b:Person) RETURN a.id, b.id", default_weight=1.0 +) +print(counted.out_weights.to_pylist()) # [2.0, 1.0, 1.0, 1.0] +``` + +The query's result is held in memory while the arrays are built, as with +[`execute`][lance_csr.CypherEngine.execute]. + ## Running an algorithm with icebug [icebug](https://github.com/Ladybug-Memory/icebug) is a fork of [NetworKit](https://networkit.github.io/) whose diff --git a/docs/typescript.md b/docs/typescript.md index 89ab4da..9d98d57 100644 --- a/docs/typescript.md +++ b/docs/typescript.md @@ -213,6 +213,7 @@ method, so your editor shows the details on hover. | `engine.csr_stats()`, `node_index_stats()` (keys such as `delta_edges`, `build_ms`) | `engine.csrStats()`, `nodeIndexStats()` (keys such as `deltaEdges`, `buildMs`) | | `engine.export_graph(rel_types, directed=False, weight="w", combine_edges="min")`, a `GraphExport` of pyarrow arrays | `await engine.exportGraph(relTypes, { directed: false, weight: "w", combineEdges: "min" })`, a `GraphExport` of apache-arrow vectors | | `engine.export_graph(weight={"ROAD": "km"}, default_weight=1.0)` | `await engine.exportGraph(undefined, { weight: { ROAD: "km" }, defaultWeight: 1 })` | +| `engine.export_subgraph(query, params, directed=False, weight="cost")` | `await engine.exportSubgraph(query, params, { directed: false, weight: "cost" })` | | `engine.dataset_versions()`, `engine.config()` | `engine.datasetVersions()`, `engine.config()` | | `engine.execute_with_vector_rerank(query, search)` | `await engine.executeWithVectorRerank(query, search)` | | `CypherQuery(text).with_config(config).with_parameter(key, value)` | `new CypherQuery(text).withConfig(config).withParameter(key, value)` | diff --git a/nodejs/native.d.ts b/nodejs/native.d.ts index f03f122..528d878 100644 --- a/nodejs/native.d.ts +++ b/nodejs/native.d.ts @@ -21,6 +21,7 @@ export declare class CypherEngine { nodeIndexStats(): Record csrStats(): Record exportGraph(relTypes: Array | undefined | null, directed: boolean, weight?: string | Record | undefined | null, combineEdges?: string | undefined | null, defaultWeight?: number | undefined | null): Promise + exportSubgraph(query: string, paramsJson: string | undefined | null, directed: boolean, weight?: string | undefined | null, combineEdges?: string | undefined | null, defaultWeight?: number | undefined | null): Promise datasetVersions(): Record executeWithVectorRerank(query: string, search: VectorSearchSpec): Promise } diff --git a/nodejs/src/cypher.ts b/nodejs/src/cypher.ts index 571e7db..9d602ad 100644 --- a/nodejs/src/cypher.ts +++ b/nodejs/src/cypher.ts @@ -470,21 +470,57 @@ export class CypherEngine { options.defaultWeight, ), ); - return { - numNodes: g.numNodes, - directed: g.directed, - nodeKeys: makeVector(g.nodeKeys), - labelRanges: Object.fromEntries( - Object.entries(g.labelRanges).map(([label, [start, end]]) => [label, [start!, end!]]), + return fromNative(g); + } + + /** + * The part of the graph a Cypher query selects, as typed arrays over dense node ids: the same + * form and edge rules as {@link CypherEngine.exportGraph}. + * + * The query returns one row per edge, with the source and target node keys as its first two + * columns. The nodes are the keys present in the result. When both columns are a labeled + * node's key, as `RETURN a.id, b.id` with `(a:Person)` and `id` its key, the ids are grouped + * per label as in `exportGraph`, so `labelRanges` is filled; otherwise all keys share one id + * space and `labelRanges` is empty. See + * [Subgraphs](https://lance-csr.hdclabs.ai/graph-algorithms/#subgraphs). + * + * @param query - A Cypher query returning the source and target keys as its first two + * columns, which must be integer types up to `int64`. + * @param params - Values for `$name` parameters, as for {@link CypherEngine.execute}. + * @param options.directed - `true` (the default) returns out-edge and in-edge arrays; `false` + * returns one set of arrays listing every edge in both directions. + * @param options.weight - A numeric column of the result holding each edge's weight, + * case-insensitive, exported as float64 in `outWeights` and `inWeights`. An edge whose + * weight is null is left out and counted in `droppedEdges`. + * @param options.combineEdges - How an edge listed more than once combines its weights, as in + * `exportGraph`. Ignored without weights. + * @param options.defaultWeight - Without `weight`, the weight of every row: `1` makes each + * edge's weight the number of rows that list it. + * @throws {@link LanceCsrError} `InvalidArgument` if the query is invalid, its first two + * columns aren't integer keys, the weight column is missing or isn't numeric, or + * `combineEdges` isn't one of the three rules; `Runtime` if the query fails while running. + */ + async exportSubgraph( + query: string, + params?: Record | null, + options: { + directed?: boolean; + weight?: string; + combineEdges?: "sum" | "min" | "max"; + defaultWeight?: number; + } = {}, + ): Promise { + const g = await call(() => + this.#inner.exportSubgraph( + query, + parametersJson(params), + options.directed ?? true, + options.weight, + options.combineEdges, + options.defaultWeight, ), - outIndptr: makeVector(g.outIndptr), - outIndices: makeVector(g.outIndices), - inIndptr: g.inIndptr ? makeVector(g.inIndptr) : null, - inIndices: g.inIndices ? makeVector(g.inIndices) : null, - outWeights: g.outWeights ? makeVector(g.outWeights) : null, - inWeights: g.inWeights ? makeVector(g.inWeights) : null, - droppedEdges: g.droppedEdges, - }; + ); + return fromNative(g); } /** The pinned version of each Lance dataset, keyed by dataset name. Arrow inputs aren't listed. */ @@ -710,3 +746,22 @@ export class CypherQuery { return `CypherQuery(${JSON.stringify(this.#query)})`; } } + +/** The native export as apache-arrow vectors over the same typed arrays. */ +function fromNative(g: native.GraphExport): GraphExport { + return { + numNodes: g.numNodes, + directed: g.directed, + nodeKeys: makeVector(g.nodeKeys), + labelRanges: Object.fromEntries( + Object.entries(g.labelRanges).map(([label, [start, end]]) => [label, [start!, end!]]), + ), + outIndptr: makeVector(g.outIndptr), + outIndices: makeVector(g.outIndices), + inIndptr: g.inIndptr ? makeVector(g.inIndptr) : null, + inIndices: g.inIndices ? makeVector(g.inIndices) : null, + outWeights: g.outWeights ? makeVector(g.outWeights) : null, + inWeights: g.inWeights ? makeVector(g.inWeights) : null, + droppedEdges: g.droppedEdges, + }; +} diff --git a/nodejs/src/types.ts b/nodejs/src/types.ts index 200cf8a..119afcd 100644 --- a/nodejs/src/types.ts +++ b/nodejs/src/types.ts @@ -95,7 +95,8 @@ export interface CsrStats { } /** - * A graph as compressed sparse rows over dense node ids, from `CypherEngine.exportGraph()`. + * A graph as compressed sparse rows over dense node ids, from `CypherEngine.exportGraph()` or + * `CypherEngine.exportSubgraph()`. * * Nodes are numbered `0` to `numNodes - 1`, and the neighbours of node `i` are * `outIndices[outIndptr[i]]` up to `outIndices[outIndptr[i + 1]]`. `nodeKeys` maps each dense @@ -108,13 +109,15 @@ export interface GraphExport { /** Whether the arrays describe a directed graph. */ directed: boolean; /** - * The key of each dense id. Each label's nodes are in the order its table is scanned; rows - * with a null key are left out. + * The key of each dense id. From `exportGraph`, each label's nodes are in the order its table + * is scanned, and rows with a null key are left out. From `exportSubgraph`, the keys present + * in the query result, sorted within each label (or within the one id space without labels). */ nodeKeys: Vector; /** * Each node label's dense ids, as `[start, end]` with `end` excluded. Labels get consecutive - * ranges in name order, so equal keys in two labels stay distinct. + * ranges in name order, so equal keys in two labels stay distinct. Empty for an + * `exportSubgraph` whose key columns couldn't be matched to labels. */ labelRanges: Record; /** Offsets into `outIndices`, `numNodes + 1` entries. */ diff --git a/nodejs/test/graph-export.test.ts b/nodejs/test/graph-export.test.ts index f21c075..47b233b 100644 --- a/nodejs/test/graph-export.test.ts +++ b/nodejs/test/graph-export.test.ts @@ -106,6 +106,25 @@ test("weight columns per type and a default weight", async () => { } }); +test("subgraph of a query", async () => { + const engine = await CypherEngine.create(config, datasets); + const query = "MATCH (a:Person)-[:KNOWS]->(b:Person) WHERE a.id >= $low RETURN a.id, b.id"; + const g = await engine.exportSubgraph(query, { low: 20 }, { directed: false }); + // 20->30 and 30->10: the keys present, sorted. + assert.deepEqual(list(g.nodeKeys), [10, 20, 30]); + assert.deepEqual(g.labelRanges, { Person: [0, 3] }); + assert.deepEqual(list(g.outIndptr), [0, 1, 2, 4]); + assert.deepEqual(list(g.outIndices), [2, 2, 0, 1]); + assert.equal(g.inIndptr, null); + // One weight per row counts the duplicate 10->20 twice. + const rows = await engine.exportSubgraph(query, { low: 0 }, { defaultWeight: 1 }); + assert.deepEqual(Array.from(rows.outWeights!.toArray()), [2, 1, 1]); + await assert.rejects( + engine.exportSubgraph("MATCH (a:Person) RETURN a.id"), + (err) => err instanceof LanceCsrError && err.code === "InvalidArgument", + ); +}); + test("unknown relationship type", async () => { const engine = await CypherEngine.create(config, datasets); await assert.rejects( diff --git a/nodejs/typedoc/api.md b/nodejs/typedoc/api.md index c8fc99d..5729199 100644 --- a/nodejs/typedoc/api.md +++ b/nodejs/typedoc/api.md @@ -298,6 +298,50 @@ without `useCsr`. Lance datasets are scanned for just those columns. See rules, or there's nothing to export; `Runtime` if a node key appears twice within a label, or a scan fails. + + +##### exportSubgraph() + +```ts +exportSubgraph( + query, + params?, + options? +): Promise; +``` + +The part of the graph a Cypher query selects, as typed arrays over dense node ids: the same +form and edge rules as [CypherEngine.exportGraph](#exportgraph). + +The query returns one row per edge, with the source and target node keys as its first two +columns. The nodes are the keys present in the result. When both columns are a labeled +node's key, as `RETURN a.id, b.id` with `(a:Person)` and `id` its key, the ids are grouped +per label as in `exportGraph`, so `labelRanges` is filled; otherwise all keys share one id +space and `labelRanges` is empty. See +[Subgraphs](https://lance-csr.hdclabs.ai/graph-algorithms/#subgraphs). + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `query` | `string` | A Cypher query returning the source and target keys as its first two columns, which must be integer types up to `int64`. | +| `params?` | `Record`\<`string`, [`Parameter`](#parameter)\> \| `null` | Values for `$name` parameters, as for [CypherEngine.execute](#execute). | +| `options?` | \{ `combineEdges?`: `"sum"` \| `"min"` \| `"max"`; `defaultWeight?`: `number`; `directed?`: `boolean`; `weight?`: `string`; \} | - | +| `options.combineEdges?` | `"sum"` \| `"min"` \| `"max"` | How an edge listed more than once combines its weights, as in `exportGraph`. Ignored without weights. | +| `options.defaultWeight?` | `number` | Without `weight`, the weight of every row: `1` makes each edge's weight the number of rows that list it. | +| `options.directed?` | `boolean` | `true` (the default) returns out-edge and in-edge arrays; `false` returns one set of arrays listing every edge in both directions. | +| `options.weight?` | `string` | A numeric column of the result holding each edge's weight, case-insensitive, exported as float64 in `outWeights` and `inWeights`. An edge whose weight is null is left out and counted in `droppedEdges`. | + +###### Returns + +`Promise`\<[`GraphExport`](#graphexport)\> + +###### Throws + +[LanceCsrError](#lancecsrerror) `InvalidArgument` if the query is invalid, its first two + columns aren't integer keys, the weight column is missing or isn't numeric, or + `combineEdges` isn't one of the three rules; `Runtime` if the query fails while running. + ##### nodeIndexStats() @@ -1629,7 +1673,8 @@ Options for explaining a query. ### GraphExport -A graph as compressed sparse rows over dense node ids, from `CypherEngine.exportGraph()`. +A graph as compressed sparse rows over dense node ids, from `CypherEngine.exportGraph()` or +`CypherEngine.exportSubgraph()`. Nodes are numbered `0` to `numNodes - 1`, and the neighbours of node `i` are `outIndices[outIndptr[i]]` up to `outIndices[outIndptr[i + 1]]`. `nodeKeys` maps each dense @@ -1645,8 +1690,8 @@ id back to its node's key. The vectors wrap typed arrays built in Rust. See | `inIndices` | `Vector`\<`Uint64`\> \| `null` | Each node's in-neighbours, sorted, without duplicates; `null` for an undirected graph. | | `inIndptr` | `Vector`\<`Uint64`\> \| `null` | Offsets into `inIndices`; `null` for an undirected graph. | | `inWeights` | `Vector`\<`Float64`\> \| `null` | The weight of each entry in `inIndices`; `null` for an undirected export, or unless `exportGraph` was given a `weight` column. | -| `labelRanges` | `Record`\<`string`, \[`number`, `number`\]\> | Each node label's dense ids, as `[start, end]` with `end` excluded. Labels get consecutive ranges in name order, so equal keys in two labels stay distinct. | -| `nodeKeys` | `Vector`\<`Int64`\> | The key of each dense id. Each label's nodes are in the order its table is scanned; rows with a null key are left out. | +| `labelRanges` | `Record`\<`string`, \[`number`, `number`\]\> | Each node label's dense ids, as `[start, end]` with `end` excluded. Labels get consecutive ranges in name order, so equal keys in two labels stay distinct. Empty for an `exportSubgraph` whose key columns couldn't be matched to labels. | +| `nodeKeys` | `Vector`\<`Int64`\> | The key of each dense id. From `exportGraph`, each label's nodes are in the order its table is scanned, and rows with a null key are left out. From `exportSubgraph`, the keys present in the query result, sorted within each label (or within the one id space without labels). | | `numNodes` | `number` | Number of nodes. Dense ids run from 0 to `numNodes - 1`. | | `outIndices` | `Vector`\<`Uint64`\> | Each node's out-neighbours, sorted, without duplicates. An undirected graph lists every edge in both directions and a self-loop once. | | `outIndptr` | `Vector`\<`Uint64`\> | Offsets into `outIndices`, `numNodes + 1` entries. | diff --git a/python/python/lance_csr/_internal/graph.pyi b/python/python/lance_csr/_internal/graph.pyi index e5db1c0..1c85ddf 100644 --- a/python/python/lance_csr/_internal/graph.pyi +++ b/python/python/lance_csr/_internal/graph.pyi @@ -169,6 +169,16 @@ class CypherEngine: combine_edges: Literal["sum", "min", "max"] = "sum", default_weight: float | None = None, ) -> GraphExport: ... + def export_subgraph( + self, + query: str, + params: dict[str, Any] | None = None, + *, + directed: bool = True, + weight: str | None = None, + combine_edges: Literal["sum", "min", "max"] = "sum", + default_weight: float | None = None, + ) -> GraphExport: ... def write_node_column( self, export: GraphExport, diff --git a/python/python/lance_csr/cypher.py b/python/python/lance_csr/cypher.py index 39aec2c..2fc2da7 100644 --- a/python/python/lance_csr/cypher.py +++ b/python/python/lance_csr/cypher.py @@ -556,6 +556,96 @@ def export_graph( ) ) + def export_subgraph[ParameterT: Parameter]( + self, + query: str, + params: dict[str, ParameterT] | None = None, + *, + directed: bool = True, + weight: str | None = None, + combine_edges: Literal["sum", "min", "max"] = "sum", + default_weight: float | None = None, + ) -> GraphExport: + """The part of the graph a Cypher query selects, as dense CSR arrays. + + Runs `query` and builds the same arrays as + [`export_graph`][lance_csr.CypherEngine.export_graph], by the same edge rules, + from its result: one row per edge, with the source and target node keys as the + first two columns. The nodes are the keys present in the result. When both + columns are a labeled node's key, as `RETURN a.id, b.id` with `(a:Person)` and + `id` its key, the ids are grouped per label as in `export_graph`, so + `label_ranges` is filled and + [`write_node_column`][lance_csr.CypherEngine.write_node_column] can write + results back; otherwise all keys share one id space and `label_ranges` is + empty. See [Graph algorithms](graph-algorithms.md#subgraphs). + + Parameters + ---------- + query : str + A Cypher query returning the source and target keys as its first two + columns, which must be integer types up to `int64`. + params : dict or None + Query parameters, as for [`execute`][lance_csr.CypherEngine.execute]. + directed : bool + Keyword-only. `True` returns out-edge and in-edge arrays; `False` returns + one set of arrays listing every edge in both directions. + weight : str or None + Keyword-only. A numeric column of the result holding each edge's weight, + case-insensitive, exported as `float64` in `out_weights` and `in_weights`. + An edge whose weight is null is left out and counted in `dropped_edges`. + combine_edges : {"sum", "min", "max"} + Keyword-only. How an edge listed more than once combines its weights, as in + `export_graph`. Ignored without weights. + default_weight : float or None + Keyword-only. Without `weight`, the weight of every row: `1.0` makes each + edge's weight the number of rows that list it. + + Returns + ------- + GraphExport + Dense node ids, their keys and the CSR arrays. + + Raises + ------ + ValueError + If the query is invalid, its first two columns aren't integer keys, the + weight column is missing or isn't numeric, or `combine_edges` isn't one of + the three rules. + RuntimeError + If the query fails while running. + + Examples + -------- + >>> import pyarrow as pa + >>> from lance_csr import CypherEngine, GraphConfig + >>> config = ( + ... GraphConfig.builder() + ... .node_table("Person", "id") + ... .rel_table("KNOWS", "Person", "Person", "src_id", "dst_id") + ... .build() + ... ) + >>> engine = CypherEngine(config, { + ... "Person": pa.table({"id": [10, 20, 30, 40]}), + ... "KNOWS": pa.table({"src_id": [10, 20, 30], "dst_id": [20, 30, 40]}), + ... }) + >>> g = engine.export_subgraph( + ... "MATCH (a:Person)-[:KNOWS]->(b:Person) WHERE a.id >= 20 " + ... "RETURN a.id, b.id" + ... ) + >>> g.node_keys.to_pylist(), g.out_indices.to_pylist() + ([20, 30, 40], [1, 2]) + """ + return GraphExport._from_inner( + self._inner.export_subgraph( + query, + params, + directed=directed, + weight=weight, + combine_edges=combine_edges, + default_weight=default_weight, + ) + ) + def write_node_column( self, export: GraphExport, diff --git a/python/python/lance_csr/export.py b/python/python/lance_csr/export.py index e37127e..3057311 100644 --- a/python/python/lance_csr/export.py +++ b/python/python/lance_csr/export.py @@ -13,7 +13,8 @@ @final class GraphExport: """A graph as compressed sparse rows over dense node ids, from - [`CypherEngine.export_graph`][lance_csr.CypherEngine.export_graph]. + [`CypherEngine.export_graph`][lance_csr.CypherEngine.export_graph] or + [`CypherEngine.export_subgraph`][lance_csr.CypherEngine.export_subgraph]. Graph-algorithm libraries such as icebug, igraph or scipy take a graph in this form: nodes numbered `0` to `num_nodes - 1`, and for each node `i` its neighbours @@ -55,8 +56,10 @@ def directed(self) -> bool: def node_keys(self) -> Int64Array: """The key of each dense id. - Each label's nodes are in the order its table is scanned; rows with a null key - are left out. + From `export_graph`, each label's nodes are in the order its table is scanned, + and rows with a null key are left out. From `export_subgraph`, the keys present + in the query result, sorted within each label (or within the one id space + without labels). """ return self._inner.node_keys @@ -65,7 +68,8 @@ def label_ranges(self) -> dict[str, tuple[int, int]]: """Each node label's dense ids, as `(start, end)` with `end` excluded. Labels get consecutive ranges in name order, so equal keys in two labels stay - distinct nodes. + distinct nodes. Empty for an `export_subgraph` whose key columns couldn't be + matched to labels. """ return self._inner.label_ranges diff --git a/python/python/tests/test_graph_export.py b/python/python/tests/test_graph_export.py index fd33553..34bab08 100644 --- a/python/python/tests/test_graph_export.py +++ b/python/python/tests/test_graph_export.py @@ -139,6 +139,67 @@ def out_weights(**kwargs) -> list[float]: engine.export_graph(weight=3) # pyright: ignore[reportArgumentType] +def test_export_subgraph(): + engine = CypherEngine(CONFIG, {"Person": NODES, "KNOWS": WEIGHTED}) + query = ( + "MATCH (a:Person)-[r:KNOWS]->(b:Person) WHERE a.id >= $low " + "RETURN a.id, b.id, r.w AS cost" + ) + g = engine.export_subgraph(query, {"low": 30}, directed=False) + assert isinstance(g, GraphExport) + # 30->10, 30->30, 50->60, 60->50: the keys present, sorted. + assert g.node_keys.to_pylist() == [10, 30, 50, 60] + assert g.label_ranges == {"Person": (0, 4)} + assert g.out_indptr.to_pylist() == [0, 1, 3, 4, 5] + assert g.out_indices.to_pylist() == [1, 0, 1, 3, 2] + assert g.out_weights is None and g.in_indptr is None + + w = engine.export_subgraph(query, {"low": 10}, weight="cost") + assert w.out_weights is not None + # The duplicate 10->20 sums 1 and 2. + assert w.out_weights.to_pylist() == [3, 4, 8, 16, 64, 128] + rows = engine.export_subgraph(query, {"low": 10}, default_weight=1.0) + assert rows.out_weights is not None + assert rows.out_weights.to_pylist() == [2, 1, 1, 1, 1, 1] + + # Computed keys can't be matched to a label: one id space, no write-back. + unlabeled = engine.export_subgraph( + "MATCH (a:Person)-[:KNOWS]->(b:Person) RETURN a.id + 0 AS s, b.id" + ) + assert unlabeled.label_ranges == {} + with pytest.raises(ValueError, match="no node labels"): + engine.write_node_column(unlabeled, "x", [0] * unlabeled.num_nodes) + + with pytest.raises(ValueError, match="integer key"): + engine.export_subgraph("MATCH (a:Person) RETURN 'x' AS s, a.id") + with pytest.raises(ValueError, match="first two columns"): + engine.export_subgraph("MATCH (a:Person) RETURN a.id") + with pytest.raises(ValueError, match="'price' not found"): + engine.export_subgraph(query, {"low": 10}, weight="price") + + +def test_export_subgraph_write_back(tmp_path): + lance.write_dataset(NODES, tmp_path / "person.lance") + lance.write_dataset(EDGES, tmp_path / "knows.lance") + engine = CypherEngine( + CONFIG, + { + "Person": lance.dataset(tmp_path / "person.lance"), + "KNOWS": lance.dataset(tmp_path / "knows.lance"), + }, + ) + g = engine.export_subgraph( + "MATCH (a:Person)-[:KNOWS]->(b:Person) WHERE a.id >= 30 RETURN a.id, b.id" + ) + engine.write_node_column(g, "in_sub", [True] * g.num_nodes) + rows = engine.execute("MATCH (p:Person) RETURN p.id, p.in_sub ORDER BY p.id") + # Nodes outside the subgraph get null. + assert rows.to_pylist() == [ + {"p.id": key, "p.in_sub": True if key in (10, 30, 50, 60) else None} + for key in (10, 20, 30, 40, 50, 60) + ] + + def test_labels_with_colliding_keys(): config = ( GraphConfig.builder()