Skip to main content

BFS

SQL function: cugraph_bfs

Official cuGraph reference: C API

Visit reachable vertices in increasing unweighted hop distance from one or more sources, returning distances and optional predecessors.

Quickstart

The call below supplies edges from registered relation target_edges with canonical src and dst columns and may include weight, and starts from source vertex 123. Substitute your own registered relations.

SELECT * FROM cugraph_bfs(edges => (SELECT src, dst FROM target_edges), source_vertex => 123, depth_limit => 4);

Inputs

Every relation is a named parenthesized SELECT subquery. The required edges role uses canonical src and dst columns; every role, its canonical columns, and their accepted Arrow types are listed under Relation arguments. Metadata validation resolves registered tables named in its JSON request.

Endpoint columns accept numeric Int32, Int64 vertex IDs or logical string Utf8, LargeUtf8, Utf8View vertex IDs; string vertex-identity outputs are canonicalized to Utf8 (native mapping Int64) while scores, distances, counts, coordinates, and opaque labels stay numeric. The shared vertex-ID contract is summarized in Vertex ID support; the concrete call-specific schema comes from gpu_validate_call.

Logical string side-input limitations:

  • edge ID columns and edge-ID predicate side inputs are not supported for logical string graphs
  • string logical vertex-domain BFS rejects edges.edge_id and edge-id predicate relations

Arguments and options

Relation arguments

ArgumentRequiredColumnsDescription
edgesyes
  • src, dst: Int32, Int64, Utf8, LargeUtf8, Utf8View
  • weight (optional): Float32, Float64
  • edge_id (optional): Int32, Int64
edge relation with canonical src and dst columns, plus optional weight and edge_id columns
sourcesno
  • vertex: Int32, Int64, Utf8, LargeUtf8, Utf8View
optional BFS source relation; exactly one of sources, source_vertex, and source_vertices is required
include_verticesno
  • vertex: Int32, Int64, Utf8, LargeUtf8, Utf8View
vertices retained by BFS predicate filtering
exclude_verticesno
  • vertex: Int32, Int64, Utf8, LargeUtf8, Utf8View
vertices removed by BFS predicate filtering
target_verticesno
  • vertex: Int32, Int64, Utf8, LargeUtf8, Utf8View
BFS target vertices required for path output or target information
include_edge_idsno
  • edge_id: Int32, Int64
edge identifiers retained by BFS predicate filtering
include_edgesno
  • src, dst: Int32, Int64, Utf8, LargeUtf8, Utf8View
  • edge_id (optional): Int32, Int64
edge predicate relation with src, dst, and optional edge_id columns

Vertex columns of sources, include_vertices, exclude_vertices, target_vertices, include_edges must use the same vertex domain as edges: the integer type of src and dst, or any listed string type when the endpoints are strings. Every edge_id column must have the integer type of src and dst; string-keyed graphs accept no edge IDs.

Named value arguments

OptionTypeDefaultConstraintsDescription
depth_limitinteger|nullnullmin 0; max 9223372036854776000optional non-negative BFS depth limit
output_modestring"raw"one of "raw", "normalized", "path"BFS output shape
return_target_infobooleanfalsewhether raw or normalized BFS output includes target information
source_vertexinteger|stringNo defaultscalar source vertex; BFS source selectors are mutually exclusive
source_verticesarrayNo defaultnon-empty homogeneous BFS source vertex array; mutually exclusive with source_vertex and sources

Graph construction options

Graph construction follows the shared defaults (directed=true, renumbering, python_cugraph policy) documented in Graph Construction Options.

Output

raw (default)

ColumnTypeNullableDescription
vertexInt64|Utf8noVertex reached or considered by the BFS traversal.
distanceInt64noHop-count distance from the nearest selected BFS source vertex.
predecessorInt64|Utf8yesPrevious vertex on the discovered BFS tree, null for selected source vertices or unreachable vertices depending on output mode.

normalized

ColumnTypeNullableDescription
vertexInt64|Utf8noVertex reached or considered by the BFS traversal.
distanceInt64yesHop-count distance from the nearest selected BFS source vertex.
predecessorInt64|Utf8yesPrevious vertex on the discovered BFS tree, null for selected source vertices or unreachable vertices depending on output mode.
reachableBooleannoWhether the vertex is reachable under normalized BFS output.

normalized_with_target_info

ColumnTypeNullableDescription
vertexInt64|Utf8noVertex reached or considered by the BFS traversal.
distanceInt64yesHop-count distance from the nearest selected BFS source vertex.
predecessorInt64|Utf8yesPrevious vertex on the discovered BFS tree, null for selected source vertices or unreachable vertices depending on output mode.
reachableBooleannoWhether the vertex is reachable under normalized BFS output.
target_foundBooleannoWhether a requested target vertex was reached by the BFS traversal.
target_distanceInt64yesHop-count distance to the requested target vertex, null when the target was not reached.

path

ColumnTypeNullableDescription
path_indexInt64noZero-based row position in the reconstructed source-to-target path.
sourceInt64|Utf8noSource vertex for the reconstructed BFS path.
targetInt64|Utf8noTarget vertex for the reconstructed BFS path.
vertexInt64|Utf8noVertex reached or considered by the BFS traversal.
distanceInt64noHop-count distance from the nearest selected BFS source vertex.

raw_with_target_info

ColumnTypeNullableDescription
vertexInt64|Utf8noVertex reached or considered by the BFS traversal.
distanceInt64noHop-count distance from the nearest selected BFS source vertex.
predecessorInt64|Utf8yesPrevious vertex on the discovered BFS tree, null for selected source vertices or unreachable vertices depending on output mode.
target_foundBooleannoWhether a requested target vertex was reached by the BFS traversal.
target_distanceInt64yesHop-count distance to the requested target vertex, null when the target was not reached.

These are generic descriptor schemas; run gpu_validate_call to get the concrete, table-specific output schema.

Examples

These examples run on the citation network demo dataset. Edges point srcdst as "cites"; BFS distance is a hop count.

Reverse the traversal by projecting named edge columns

Following citations forward (srcdst) walks into a paper's reference ancestry. Projecting dst AS src, src AS dst into the named edges relation traverses the same edges in the opposite direction (from a paper to the papers that cite it, and then their citers) without building a new table. The sources relation resolves the start vertex from AlexNet's title and year, so no paper id appears in the query; each BFS generation is one hop outward in citing papers:

SELECT b.distance, COUNT(*) AS papers, ROUND(AVG(p.year), 1) AS avg_year
FROM cugraph_bfs(
edges => (SELECT dst AS src, src AS dst FROM citation_edges_by_dst),
sources => (SELECT paper_id AS vertex FROM papers
WHERE title = 'ImageNet Classification with Deep Convolutional Neural Networks'
AND year = 2012),
depth_limit => 3, output_mode => 'normalized') b
JOIN papers p ON p.paper_id = b.vertex
WHERE b.reachable
GROUP BY b.distance
ORDER BY b.distance;
distancepapersavg_year
012012.0
112,1852017.5
267,5172017.9
371,5412017.8

Three citation generations reach ~151k papers. (The reversed traversal reads citation_edges_by_dst, which is clustered by dst, so the scan prunes well.)

Path mode with a SQL-defined target

output_mode: "path" reconstructs the shortest hop chain between the source and a target. Both endpoints are relations, so a WHERE clause on papers selects each one by title and year; target_vertices must resolve to exactly one row. This query traces the reference path from BERT (2018) back to LSTM (1997). The year predicate matters here: the corpus also holds a 2019 conference record titled identically to the BERT preprint.

SELECT b.path_index, b.distance, p.year, p.title
FROM cugraph_bfs(
edges => (SELECT src, dst FROM citation_edges),
sources => (SELECT paper_id AS vertex FROM papers
WHERE title = 'BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding'
AND year = 2018),
output_mode => 'path',
target_vertices => (SELECT paper_id AS vertex FROM papers
WHERE title = 'Long short-term memory' AND year = 1997)) b
JOIN papers p ON p.paper_id = b.vertex
ORDER BY b.path_index;
path_indexdistanceyeartitle
002018BERT: Pre-training of Deep Bidirectional Transformers…
112015Semi-supervised Sequence Learning
221997Long short-term memory

Two hops of references separate BERT from LSTM. Several two-hop chains exist, and path output returns one of them: other runs pass through SemEval-2017 Task 1 or Aligning Books and Movies instead.

Multi-source BFS from a seed view

Passing the named sources relation starts the traversal from every row of a SQL result. Here the three CNN classics (AlexNet, VGG, ResNet) form one combined frontier, so distance measures hops from the nearest of the three founding papers. Each title is paired with its year because the corpus also holds a 2015 preprint record of the ResNet paper under the same title:

CREATE OR REPLACE VIEW cnn_founders AS
SELECT paper_id AS vertex FROM papers
WHERE (title = 'ImageNet Classification with Deep Convolutional Neural Networks' AND year = 2012)
OR (title = 'VERY DEEP CONVOLUTIONAL NETWORKS FOR LARGE-SCALE IMAGE RECOGNITION' AND year = 2014)
OR (title = 'Deep Residual Learning for Image Recognition' AND year = 2016);

SELECT b.distance, COUNT(*) AS papers
FROM cugraph_bfs(
edges => (SELECT dst AS src, src AS dst FROM citation_edges_by_dst),
sources => (SELECT vertex FROM cnn_founders), depth_limit => 2,
output_mode => 'normalized') b
JOIN papers p ON p.paper_id = b.vertex
WHERE b.reachable
GROUP BY b.distance
ORDER BY b.distance;
distancepapers
03
128,776
269,038

Title-keyed vertices on a small subgraph

Logical string endpoints let a graph use titles as vertex IDs, so results come back readable without a join to papers. That is sound only where each title names one paper, and the demo dataset repeats 193,894 titles, which is why the examples above keep paper_id as the vertex domain. On a small subgraph the trade-off can be measured first. The reference ancestry of Attention Is All You Need (the seed, its 22 references, and every paper those cite) spans 370 papers but only 358 distinct titles:

CREATE OR REPLACE VIEW attention_ancestry AS
WITH origins AS (
SELECT paper_id FROM papers
WHERE title = 'Attention is all you need' AND year = 2017
UNION ALL
SELECT e.dst FROM citation_edges e
JOIN papers p ON p.paper_id = e.src
WHERE p.title = 'Attention is all you need' AND p.year = 2017)
SELECT e.src, e.dst
FROM citation_edges e JOIN origins o ON o.paper_id = e.src;

SELECT COUNT(DISTINCT n.paper_id) AS papers, COUNT(DISTINCT p.title) AS titles
FROM (SELECT src AS paper_id FROM attention_ancestry
UNION SELECT dst FROM attention_ancestry) n
JOIN papers p ON p.paper_id = n.paper_id;
paperstitles
370358

The 12 missing titles each belong to two records, mostly a preprint and its proceedings version. Keying the edges by title merges every such pair into one vertex. For a reading list that merge is intended, since both records are one work; for unrelated papers that share a generic title it would corrupt the topology. Here BFS starts from a title literal, and vertex comes back as Utf8:

SELECT b.distance, b.vertex
FROM cugraph_bfs(
edges => (SELECT ps.title AS src, pd.title AS dst
FROM attention_ancestry a
JOIN papers ps ON ps.paper_id = a.src
JOIN papers pd ON pd.paper_id = a.dst),
source_vertex => 'Attention is all you need', output_mode => 'normalized') b
WHERE b.distance <= 1
ORDER BY b.distance, b.vertex
LIMIT 6;
distancevertex
0Attention is all you need
1A Decomposable Attention Model for Natural Language Inference
1A Deep Reinforced Model for Abstractive Summarization
1Adam: A Method for Stochastic Optimization
1Deep Recurrent Models with Fast-Forward Connections for Neural Machine Translation
1Deep Residual Learning for Image Recognition

All 358 titles are reachable: 22 at distance 1 and 335 at distance 2. String graphs reject edge_id columns and edge-ID predicate relations; see the Vertex ID support matrix.

Limits

  • source_vertices and the sources relation are multi-source BFS, not one BFS per source
  • source_vertices and the sources relation must contain at most one source per connected component
  • raw/normalized output does not expose origin source per vertex
  • string logical vertex-domain BFS rejects edges.edge_id and edge-id predicate relations
  • path output requires exactly one target row at execution time
  • descriptor option schema is typed registry metadata; validate_call remains the authoritative call-specific checker

To dry-run validate relation metadata, column types, and options without execution, see gpu_validate_call.