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
72 changes: 56 additions & 16 deletions crates/lance-csr-node/src/engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,28 @@ pub struct GraphExport {
pub dropped_edges: i64,
}

impl From<lance_csr::GraphExport> 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<T: arrow_array::types::ArrowPrimitiveType>(
array: arrow_array::PrimitiveArray<T>,
Expand Down Expand Up @@ -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<String>,
directed: bool,
weight: Option<String>,
combine_edges: Option<String>,
default_weight: Option<f64>,
) -> napi::Result<GraphExport> {
let combine = combine_edges
.as_deref()
.map(str::parse::<lance_csr::CombineEdges>)
.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]
Expand Down
34 changes: 34 additions & 0 deletions crates/lance-csr-python/src/graph.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<String>,
combine_edges: &str,
default_weight: Option<f64>,
) -> PyResult<GraphExport> {
let combine = combine_edges
.parse::<lance_csr::CombineEdges>()
.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,
Expand Down
36 changes: 34 additions & 2 deletions crates/lance-csr/src/engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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]>,
Expand All @@ -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<String, JsonValue>,
directed: bool,
weights: Option<&crate::graph_export::EdgeWeights>,
) -> Result<crate::graph_export::GraphExport> {
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.
///
Expand Down
Loading
Loading