GQL

Decomposing path into steps in GQL

When working with Property Graphs, resolving the data path aka. decomposing Graph path is key to understanding the path traversed by a MATCH query in GQL. To facilitate this unnesting / flattening of path data, GQL provides few options. We will look at two options and apply them to following Graph to unnest the SHORTEST path between Alice and Diana i.e. Alice -> Chalie -> Diana

Let’s start by creating a sample Sample Graph:

create graph social_network {
  NODE PERSON ({name STRING, age int}), 
  EDGE FOLLOWS ()-[]->()
};
use graph social_network;

SHOW NODE SCHEMA;
SHOW EDGE SCHEMA;
INSERT (n1:PERSON {_id:'alice', name: "Alice", age:25})
  , (n2:PERSON {_id:'bob', name: "Bob", age:30})
  , (n3:PERSON {_id:'diana', name: "Diana", age:28})
  , (n4:PERSON {_id:'charlie', name: "Charlie", age:32});
MATCH (n1:PERSON {_id:'alice'})
  , (n2:PERSON {_id:'bob'})
  , (n3:PERSON {_id:'diana'})
  , (n4:PERSON {_id:'charlie'})
INSERT (n1)-[e1:FOLLOWS]->(n2)
  , (n2)-[e2:FOLLOWS]->(n1)
  , (n2)-[e3:FOLLOWS]->(n4)
  , (n1)-[e4:FOLLOWS]->(n4)
  , (n3)-[e5:FOLLOWS]->(n4)
  , (n4)-[e6:FOLLOWS]->(n3)
  , (n3)-[e7:FOLLOWS]->(n2) 
RETURN n1, n2, n3, n4;

First let’s use pnodes function to get the unnested path as a JSON.

MATCH paths =  SHORTEST 1 (n1 {_id:'alice'})-[links]->{0,4}(n2 {_id:'diana'}) 
LET length = PATH_LENGTH(paths)
RETURN pnodes(paths);

This will output a JSON array as following:

    [{"schema":"PERSON","id":"alice","uuid":"5116091375716139010","values":{"age":25,"name":"Alice"}},{"schema":"PERSON","id":"charlie","uuid":"11961562809319292933","values":{"age":32,"name":"Charlie"}},{"schema":"PERSON","id":"diana","uuid":"16789421609860464644","values":{"age":28,"name":"Diana"}}]

Another way to UNNEST is to produce one row per hop. We can use the FOR loop for this

MATCH paths =  (n1 {_id:'alice'})-[links]->{0,4}(n2 {_id:'diana'})
FOR link in links
RETURN link;

This will output:

Notice that we used Variable Length Path Pattern {0,4} in the aforementioned query. GQL supports the following Variable Length Path Patterns:

QuantifierDescription
{n}Exactly n
{n, m}Between n and m (inclusive)
{, m}Between 0 and m (inclusive)
{m,} m (inclusive) or higher

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *