6.2 Loading a Subgraph Using PGQL Queries

You can create an in-memory subgraph from a SQL property graph using the PgSqlSubgraphReader API.

You can specify the subgraph to be loaded in one or more PGQL queries. Each of these PGQL queries will be executed on the database and all the matched vertices and edges will be loaded as part of the subgraph. Therefore, vertices and edges will be loaded only if they match at least one of the queries.

Also, note that you can only create subgraphs from SQL property graphs that exist in the current database user schema.

The following example creates a subgraph from a SQL property graph using multiple PGQL queries:

opg4j> var graph = session.readSubgraph().
...>     fromPgSql("STUDENT_NETWORK").
...>     queryPgql("MATCH (v1 IS Person)-[e IS friends]->(v2 IS Person) WHERE id(v1) = 'PERSONS(1)'").
...>     queryPgql("MATCH (v:Person) WHERE id(v) = 'PERSONS(2)'").
...>     load()
graph ==> PgxGraph[name=STUDENT_NETWORK_4,N=3,E=1,created=1681009569883]
PgxGraph graph = session.readSubgraph()
  .fromPgSql("STUDENT_NETWORK")
  .queryPgql("MATCH (v1 IS Person)-[e IS friends]->(v2 IS Person) WHERE id(v1) = 'PERSONS(1)'")
  .queryPgql("MATCH (v:Person) WHERE id(v) = 'PERSONS(2)'")
  .load();
>>> graph = session.read_subgraph_from_pg_sql("STUDENT_NETWORK",
...     ["MATCH (v1 IS Person)-[e IS friends]->(v2 IS Person) WHERE id(v1) = 'PERSONS(1)'",
...      "MATCH (v:Person) WHERE id(v) = 'PERSONS(2)'"])
>>> graph
PgxGraph(name: STUDENT_NETWORK, v: 3, e: 1, directed: True, memory(Mb): 0)

Loading Subgraphs with Custom Names

By default, the new subgraph gets created with the same name as the SQL property graph. Alternatively, if you want to load a subgraph with a custom name, then you can configure the subgraph name as shown:

opg4j> var graph = session.readSubgraph().
...>     fromPgSql("STUDENT_NETWORK").
...>     queryPgql("MATCH (v1 IS Person)-[e IS friends]->(v2 IS Person) WHERE id(v1) = 'PERSONS(1)'").
...>     queryPgql("MATCH (v:Person) WHERE id(v) = 'PERSONS(2)'").
...>     load("student_subgraph")
graph ==> PgxGraph[name=student_subgraph,N=3,E=1,created=1681010160515]
PgxGraph graph = session.readSubgraph()
  .fromPgSql("STUDENT_NETWORK")
  .queryPgql("MATCH (v1 IS Person)-[e IS friends]->(v2 IS Person) WHERE id(v1) = 'PERSONS(1)'")
  .queryPgql("MATCH (v:Person) WHERE id(v) = 'PERSONS(2)'")
  .load("student_subgraph");
>>> graph = session.read_subgraph_from_pg_sql("STUDENT_NETWORK",
...     ["MATCH (v1 IS Person)-[e IS friends]->(v2 IS Person) WHERE id(v1) = 'PERSONS(1)'",
...      "MATCH (v:Person) WHERE id(v) = 'PERSONS(2)'"],
...      graph_name="student_subgraph")
>>> graph
PgxGraph(name: student_subgraph, v: 3, e: 1, directed: True, memory(Mb): 0)