OCGraph Python Library
The ocient_graph module brings a programming model (similar to Apache® Spark™ GraphX) to the Ocient® System directly from Python® using the pyocient driver. The module treats a graph as two relational tables, one for vertices (nodes) and one for edges (directed links). This module provides a composable API for graph transformations, neighborhood analytics, and iterative algorithms (e.g., Pregel, PageRank).
The API validates inputs, avoids destructive changes by materializing results into new tables, supports optional indexing for performance, and follows Ocient SQL conventions. The package installs separately from pyocient and exposes a Python-native interface that mirrors the Java® library. For details, see OCGraph Java Library.
Installation
Use pyocient for connectivity and ocient_graph for graph APIs. The graph library is a separate package that depends on pyocient. For a tutorial about installing and using pyocient, see Ocient Python Module: pyocient.
Install and Import
Install the ocient_graph module.
Import the module.
Data Model Requirements
Database tables that use the OCGraph Python library must adhere to this structure. In addition to the listed requirements, tables can include other columns.
Subgraph and Filtering
Use a subgraph or various filters to restrict a graph to relevant vertices and edges. These functions create filtered copies or masked intersections, preserving schema and optional indexes for performance.
subgraph
Creates filtered vertex and edge tables using vertex and triplet predicates, retaining only edges with endpoints that remain after vertex filtering. The function creates the requested indexes and performs best-effort cleanup in the event of failure.
Syntax
Example Create an active customer subgraph that includes only purchases exceeding $50 where the source and destination share a region.
filter_vertices
Creates a filtered subgraph by selecting vertices that match a predicate while retaining only edges with endpoints that are in the filtered vertex set.
Syntax
Example Filter US customers and retain edges with endpoints that remain in the filtered vertex set.
filter_edges
Creates a filtered edges table by selecting edges that match a predicate.
Syntax
Example
This example demonstrates how to create a filtered edges table from an existing purchases edge set by keeping only edges that meet a business rule (weight > 0.5 and ACTIVE). Then, the filterEdges method indexes the result on the srcid and destid columns for faster lookups.
mask
Creates a masked subgraph by intersecting two graphs. Vertices intersect if the vertex identifier is present in both graphs. Edges intersect when the srcid and destid values are present in both graphs.
The function creates a masked subgraph from rows that intersect with each other. The function copies rows that intersect from the graph defined by the arguments input_vertices_table and input_edges_table, including any attributes.
You can optionally create indexes on the result subgraph tables.
Syntax
Example
Create a masked subgraph by intersecting two graphs. The example copies vertices and edges that are present in both graphs, along with the remaining endpoints.
Transformations
Construct new vertex or edge tables by computing derived columns, reversing direction, or aggregating duplicates. These functions do not change the original inputs. Instead, the functions materialize new results.
map_vertices
Creates a new vertices table with the identifier id and computed columns. Use the result_column_expressions argument to calculate additional columns. This function can also add indexes before inserting data.
Syntax
Example
Create a new vertices table with two new columns, name_upper and is_vip, and generate indexes for the id and name_upper columns.
map_edges
Creates a new edges table with srcid, destid, and any additional computed columns. Expressions should refer to input edge columns by their original names, and each computed expression should include an AS alias keyword.
Syntax
Example
Create a new edges table with two columns, discounted_amount and big_txn, and generate indexes for the srcid and destid columns.
map_triplets
Creates a new edges table with computed columns that reference a (source vertex), b (edge), and c (destination vertex). The output automatically includes b.srcid and b.destid columns.
Syntax
Example
Create a new triplet table from the vertices and edges tables with the amount and same_country columns, and generate indexes for the src and destid columns.
reverse_edges
Creates a new edges table with the srcid and destid columns reversed, preserving other columns. Use this function to traverse a graph in the opposite direction.
Syntax
Example
Transform edge direction by reversing the srcid and destid columns. The example also creates indexes for these columns.
group_edges
Groups duplicate rows of the srcid and destid columns, producing one row for each unique pair of values in a new edges table. This function performs aggregations based on one or more SQL expressions.
Syntax
Example
Create a new edge table that includes SQL aggregations for counting unique transactions txn_count and total sums total_amount. Also, this function generates indexes for the src and destid columns.
Triplets
Produce triplet representations that are made of a (source vertex), b (edge), and c (destination vertex), either as a logical view or a materialized table for downstream queries.
create_triplets_view
Creates a view that combines the edge table with the source and destination vertex attributes. This view is useful for analyzing relationships without having to repeatedly join tables. The view includes these columns:
- All original edge columns (including the
srcidanddestidcolumns). - All source-vertex columns except
id. Source-vertex column names have thesrc_prefix. - All destination-vertex columns except
id. Destination-vertex column names have thedest_prefix.
Use the create_triplets_table function instead if you want to create a materialized table with indexes instead of a view.
Syntax
Example Create a triplets view to inspect edges with joined source and destination vertex attributes.
create_triplets_table
Creates a materialized table that combines the edge table with the source and destination vertex attributes. This table is useful for analyzing relationships without having to repeatedly join tables. The created table includes these columns:
- All original edge columns (including the
srcidanddestidcolumns). - All source-vertex columns except
id. Source-vertex column names have thesrc_prefix. - All destination-vertex columns except
id. Destination-vertex column names have thedest_prefix.
Use the create_triplets_view function if you want to create a view instead of a new table.
Syntax
Example
Create a new table for triplets. Generate indexes for the src_id and dest_id columns.
Degrees
Compute degree metrics for each vertex from the edges table. These functions produce small vertex tables suitable for joins and analytics.
in_degrees
Computes how many edges point to each vertex in an edge table by counting how many times each unique destid value appears. The result table has two columns: id (the destination vertex) and in_degree (the count).
Syntax
Example
Compute in-degrees per vertex and generate an index on the id column.
out_degrees
Computes how many edges originate from each vertex in an edge table by counting how many times each unique srcid value appears. The result table has two columns: id (the source vertex) and out_degree (the count).
Syntax
Example
Compute the out-degrees count for each vertex and generate an index on the id column.
degrees
Computes the total degrees (in-degrees and out-degrees) for each vertex in an edge table by counting how many times each unique srcid and destid value appears. The result table has two columns: id (the destination or source vertex) and degree (the count).
Syntax
Example
Compute total degrees for each vertex and generate an index on the id column.
Vertex Extraction and Joins
Build vertex sets from edges and combine vertex attributes across tables. These functions are useful for shaping vertex properties and consolidating features.
from_edges
Builds a vertices table from an edges table by extracting the unique source and destination identifiers.
This function can optionally compute additional columns using SQL expressions by referencing the unique identifier as ids.id.
The created table always contains the id column with one additional column per expression.
Syntax
Example
Create a vertices table from edge endpoints and add a bucket column that assigns each vertex to one of 10 buckets. Generate an index for the id and bucket columns.
join_vertices
Merges two vertices tables by retaining every row from a primary table (input_vertices_table) and selectively updating rows that also appear in the modification table (modification_vertices_table). The merged table includes all vertices from the primary table that do not appear in the modification table.
For vertices that appear in both tables, the function must include a list of expressions (resultAttributeExpressions) in the same column order for every non-identifier column in the merged result table. These SQL expressions can add computations to columns, or simply add aliases if no changes are needed. Each expression can reference columns from the primary table (using alias a) or from the modification table (using alias b).
Syntax
Example
Merge vertex attributes and generate indexes for the id and status columns. This example includes two SQL expressions to update the status and score columns based on the modification vertex table using the COALESCE SQL reference function.
inner_join_vertices
Performs an inner join on two vertex tables using an equality comparison a.id = b.id. The result table automatically includes the id column from the first table.
The function must include a list of SQL expressions (result_attribute_expressions) in the same column order for every non-identifier column in the merged result table. These SQL expressions can add computations to columns, or simply add aliases if no changes are needed. Each expression can reference columns from the primary table using the alias a or from the modification table using the alias b.
Syntax
Example
Create an inner join between two vertex tables and generate an index on the id column.
outer_join_vertices
Performs a left outer join between two vertices tables using an equality comparison a.id = b.id. The result table includes all rows from the left table. For left-table rows that have no match in the right table, any expression that reads columns from the right table with the alias b evaluates to NULL (while expressions that only read the table with the alias a remain non-NULL as usual).
The method must include a list of SQL expressions (result_attribute_expressions) in the same column order for every non-identifier column in the merged result table. These SQL expressions can add computations to columns, or simply add aliases if no changes are needed. Each expression can reference columns from the primary table using the alias a or from the modification table using the alias b.
Syntax
Example
Perform a left outer join on two vertices tables and generate an index on the id column.
collect_neighbors
For each vertex in a table, this function collects information on neighbors (identifier and any attributes) as an array of tuples. For a specified direction (IN, OUT, or BOTH), the function aggregates tuples representing each neighboring vertex into an array.
The direction types are:
IN— Neighbors with edges pointing to the vertex (edges wheredestid = id).OUT— Neighbors that the vertex points to (edges wheresrcid = id).BOTH— Union ofINandOUTwith neighbors from incoming (destid = id) and outgoing (srcid = id) edges.
The result table has the columns id (the vertex identifier) and neighbors (an array of tuples representing each neighbor).
If an error occurs after table creation, the function drops the result table.
Syntax
Example
Collect incoming neighbors for each vertex and generate an index on the id column. The direction argument set to IN collects neighbors pointing to id.
collect_edges
For each vertex in a table, this function collects an array of adjacent edge rows based on the specified direction. The result table has two columns: id (the vertex identifier) and edges (an array of tuples, each tuple containing all columns from the edges table for a connected edge).
The direction types are:
IN— Edges pointing to the vertex (edges wheredestid = id).OUT— Edges originating from the vertex (edges wheresrcid = id).BOTH— Union ofINandOUTthat includes edges from incoming (destid = id) and outgoing (srcid = id) directions. This direction retains duplicates.
If an error occurs after table creation, the function drops the result table.
Syntax
Example
Collect outgoing edges per vertex. The example sets the direction to OUT to collect edges from id.
Algorithms
High-level graph algorithms that iterate over the graph structure to produce labels, components, or counts.
label_propagation
Executes the Label Propagation Algorithm (LPA) to assign community labels to vertices.
Each vertex starts with its own identifier as its label. For a number set by the maxIterations argument, each vertex updates its label to the most frequent label among its neighbors. The algorithm determines ties by choosing the smallest label. The algorithm uses temporary tables for intermediate results and drops these tables when the process completes or if it fails. Isolated vertices retain their initial label. The final table stores id and label columns and can include indexes.
Syntax
Example
Run label propagation for 10 iterations and assign labels to vertices. Generate an index on the id column.
connected_components
Identifies the connected components of an undirected graph. This algorithm configures a Pregel computation in which each vertex initially sets its component label equal to its own identifier id.
In each iteration, vertices send their component label to neighbors. Each vertex updates based on the aggregated minimum value of its current component label and any received values. The process repeats until no more updates occur or when it reaches the maximum specified number of iterations (max_iterations).
The result table maps each vertex id to its final component label.
Syntax
Example
Compute connected components for a maximum of 20 iterations and generate an index on the id column.
strongly_connected_components
Computes strongly connected components (SCC) in a directed graph. This function runs a recursive algorithm that partitions vertices into subsets where every vertex is reachable from other vertices in the same subset.
This function uses recursive partitioning. The algorithm selects a pivot (typically the minimum identifier id), computes its predecessor set (vertices that can reach the pivot), and its descendant sets (vertices reachable from the pivot). Then, the function identifies the SCC as their intersection, removes that SCC from the graph, and recurses on the remainder until all vertices have been assigned to an SCC. The output contains columns for the id and component identifiers (the minimum id in the SCC).
The function creates temporary tables in the result schema to store intermediate results. This function drops these tables when the computation completes or fails. The final result table contains two columns: id (vertex identifier) and component (the minimum vertex identifier in its SCC subset).
Syntax
Example
Compute the SCC and generate an index on the id column.
TriangleCount
TriangleCount identifies all 3-cycles (triangles) in the graph and counts how many distinct triangles each vertex participates in.
The algorithm first builds a canonical, undirected edge set by ensuring srcid < destid and removing duplicates to prevent double-counting. If your input edges are already canonicalized and deduplicated, use TriangleCount.run_pre_canonicalized to skip preprocessing for faster performance.
The function then counts triangles (a, b, c) where a < b < c by intersecting neighbor lists and aggregates per-vertex participation to produce a result table with the id and triangle_count columns.
run syntax
run_pre_canonicalizedsyntax
Examples
Count Triangles Usingrun
Canonicalize the raw edges internally, count unique triangles, and write per-vertex triangle counts with an index on the id column.
Count Triangles Usingrun_pre_canonicalized
Use a pre-canonicalized, deduplicated edge table to count triangles and write per-vertex triangle counts with an index on the id column.
pregel
Provides a generic vertex‑centered iteration framework for custom graph algorithms, similar to the Pregel model.
Each iteration updates vertex states by sending messages along edges and then aggregating these messages to compute new states. The algorithm continues iterating until it reaches convergence (no state changes or no messages produced) or a specified iteration cap.
The algorithm uses multiple specified SQL expressions.
Syntax
Example
Run a simple Pregel computation summing incoming edge amounts into the vertex state for 10 iterations at most, and generate an index on the id column.
Paths & Ranking
These functions include the shortest-path and PageRank algorithms.
shortest_paths
Computes the shortest distance from every vertex to each set of landmark vertices using an iterative relaxation algorithm. The algorithm resembles Bellman–Ford but simultaneously handles multiple destinations.
Each landmark starts at distance 0 and all others at positive infinity. On each iteration, the algorithm examines every edge and checks whether traveling through the connected neighbor would yield a shorter route to a landmark. If a shorter route exists, the algorithm updates the distance of the source vertex. The process stops when no distances improve or the algorithm reaches the maximum number of iterations.
After the process finishes, the algorithm writes a result table with the srcid, destid, and distance columns.
Syntax
Example
Compute distances from landmarks and generate indexes on the src and dest columns.
static_page_rank
Computes PageRank scores for each vertex over a fixed number of iterations.
The algorithm follows the standard PageRank formula with a reset probability (reset_prob) and uses common table expressions to calculate contributions from incoming edges and redistribute ranks from dangling nodes.
The algorithm supports two variants:
- Standard PageRank — All vertices start with rank
1.0/N, whereNis the number of vertices. Specify this variant ifpersonalizationSrcIdisnull. - Personalized PageRank — The specified vertex starts with a rank of
1.0, while others start with a rank of0.0. Specify this variant ifpersonalizationSrcIdis a vertex identifier.
After running PageRank for a fixed number of iterations, the function writes a result vertices table containing all original vertex columns with a new PageRank scoring column.
Syntax
Example
Run fixed-iteration PageRank and generate an index on the id column. This example uses a high reset probability reset_prob of 0.85 to ensure the ranking concentrates on highly linked regions.
dynamic_page_rank
Computes PageRank scores until convergence based on a specified threshold value (tolerance). Unlike the static_page_rank function, this algorithm runs iterations until the sum of absolute differences between ranks in successive iterations is less than or equal to the tolerance value. The algorithm handles personalization similarly to static_page_rank. At each iteration, the function uses the PageRank formula, collects rank values, and redistributes them.
The algorithm supports two variants:
- Standard PageRank — All vertices start with rank
1.0/N, whereNis the number of vertices. Specify this variant ifpersonalizationSrcIdisnull. - Personalized PageRank — The specified vertex starts with a rank of
1.0, while others start with a rank of0.0. Specify this variant ifpersonalizationSrcIdis a vertex identifier.
After running PageRank until the system reaches the tolerance threshold, the function writes a vertices table containing all the original vertex columns with a new PageRank scoring column.
Syntax
Example
Run dynamic PageRank to convergence and generate an index on the id column. This example uses a low tolerance value of 1.0e-6, which generates high-precision rankings but requires more computing resources.
Bibliography
Pregel: A System for Large-Scale Graph Processing.” Accessed November 18, 2025. https://research.google/pubs/pregel-a-system-for-large-scale-graph-processing/.

