The GSQL Query Language includes a comprehensive set of control flow statements to empower sophisticated graph traversal and data computation: IF/ELSE, CASE, WHILE, and FOREACH.
Differences in Block Syntax
Note that any of these statements can be used as a query-body statement or as a DML-sub level statement.
If the control flow statement is at the query-body level, then its block(s) of statements are query-body statements ( queryBodyStmts ). In a queryBodyStmts block , each individual statement ends with a semicolon, so there is always a semicolon at the end.
If the control flow statement is at the DML-sub level, then its block(s) of statements are DML-sub statements ( DMLSubStmtList ). In a DMLSubStmtList block, a comma separates statements, but there is no punctuation at the end.
The "Statement Types" subsection in the Chapter on "CREATE / INSTALL / RUN / SHOW / DROP QUERY" has a more detailed general example of the difference between queryBodyStmts and DMLSUbStmts.
IF Statement
The IF statement provides conditional branching: execute a block of statements ( queryBodyStmts or DMLSubStmtList ) only if a given condition is true. The IF statement allows for zero or more ELSE-IF clauses, followed by an optional ELSE clause. The IF statement can be used either at the query-body level or at the DML-sub-statement level. (See the note about differences in block syntax .)
IF syntax
queryBodyIfStmt := IF condition THEN queryBodyStmts [ELSE IF condition THEN queryBodyStmts ]* [ELSE queryBodyStmts ] END
DMLSubIfStmt := IF condition THEN DMLSubStmtList [ELSE IF condition THEN DMLSubStmtList ]* [ELSE DMLSubStmtList ] END
If a particular IF condition is not true, then the flow proceeds to the next ELSE IF condition. When a true condition is encountered, its corresponding block of statements is executed, and then the IF statement terminates (skipping any remaining ELSE-IF or ELSE clauses). If an ELSE-clause is present, its block of statements are executed if none of the preceding conditions are true. Overall, the functionality can be summarized as "execute the first block of statements whose conditional test is true."
IF semantics
# ifthenIF x ==5THEN y =10; END; # y is assigned to10 only if x is5.# ifthenelseIF x ==5THEN y =10; # y is10 only if x is5.ELSE y =20; END; # y is20 only if x isNOT5.#ifwithELSEIFIF x ==5THEN y =10; # y is10 only if x is5.ELSEIF x ==7THEN y =5; # y is5 only if x is7.ELSE y =20; END; # y is20 only if x isNOT5andNOT7.
Example 1. countFriendsOf2.gsql : Simple IF-ELSE at query-body level
# count the number of friends a person has, and optionally include coworkers in that countCREATE QUERY countFriendsOf2(vertex<person> seed, BOOL includeCoworkers) FOR GRAPH friendNet{ SumAccum<INT> @@numFriends =0;start= {seed};IF includeCoworkers THEN friends =SELECT v FROMstart-((friend | coworker):e)-> :v ACCUM @@numFriends +=1;ELSE friends =SELECT v FROMstart-(friend:e)-> :v ACCUM @@numFriends +=1;END;PRINT @@numFriends, includeCoworkers;}
# determine if a user is active in terms of social networking (i.e., posts frequently)CREATE QUERY calculateActivity(vertex<person> seed) FOR GRAPH socialNet{ SumAccum<INT> @@numberPosts =0;start= {seed}; result =SELECT postVertex FROMstart-(posted:e)-> :postVertex ACCUM @@numberPosts +=1;IF @@numberPosts <2THENPRINT"Not very active";ELSEIF @@numberPosts <3THENPRINT"Semi-active";ELSEPRINT"Very active";END;}
Example 2 Results for Query calculateActivity
GSQL > RUN QUERY calculateActivity("person1"){"error": false,"message": "","version": {"schema": 0,"api": "v2" },"results": [{"Not very active": "Not very active"}]}GSQL > RUN QUERY calculateActivity("person5"){"error": false,"message": "","version": {"schema": 0,"api": "v2" },"results": [{"Semi-active": "Semi-active"}]}
Example 3. Nested IF at query-body level
# use a more advanced activity calculation, taking into account number of posts# andnumber of likes that a user madeCREATE QUERY calculateInDepthActivity(vertex<person> seed) FOR GRAPH socialNet{ SumAccum<INT> @@numberPosts =0; SumAccum<INT> @@numberLikes =0;start= {seed}; result =SELECT postVertex FROMstart-(posted:e)-> :postVertex ACCUM @@numberPosts +=1; result =SELECT likedPost FROMstart-(liked:e)-> :likedPost ACCUM @@numberLikes +=1;IF @@numberPosts <2THENIF @@numberLikes <1THENPRINT"Not very active";ELSEPRINT"Semi-active";END;ELSEIF @@numberPosts <3THENIF @@numberLikes <2THENPRINT"Semi-active";ELSEPRINT"Active";END;ELSEPRINT"Very active";END;}
Example 3 Results for Query calculateInDepthActivity
# give each user post an accumulated rating based on the subjectand how many likes it has# This query is equivalent to the query ratePosts shown aboveCREATE QUERY ratePosts2() FOR GRAPH socialNet { SumAccum<INT> @rating =0; allPeople = {person.*}; results =SELECT v FROM allPeople -(:e)-> post:v ACCUM IF e.type =="posted"THENIF v.subject =="cats"THEN v.@rating +=-1 # -1if post is about catsELSEIF v.subject =="Graphs"THEN v.@rating +=2 # +2if post is about graphsELSEIF v.subject =="tigergraph"THEN v.@rating +=10 # +10if post is about tigergraphENDELSEIF e.type =="liked"THEN v.@rating +=3 # +3 each time post was likedENDORDER BY v.@rating DESCLIMIT5;PRINT results;}
The CASE statement provides conditional branching: execute a block of statements only if a given condition is true. CASE statements can be used as query-body statements or DML-sub-statements. (See the note about differences in block syntax .)
CASE syntax
queryBodyCaseStmt :=CASE (WHEN condition THEN queryBodyStmts)+ [ELSE queryBodyStmts] END | CASE expr (WHEN constant THEN queryBodyStmts)+ [ELSE queryBodyStmts] ENDDMLSubCaseStmt :=CASE (WHEN condition THEN DMLSubStmtList)+ [ELSE DMLSubStmtList] END | CASE expr (WHEN constant THEN DMLSubStmtList)+ [ELSE DMLSubStmtList] END
One CASE statement contains one or more WHEN-THEN clauses, each WHEN presenting one expression. The CASE statement may also have one ELSE clause whose statements are executed if none of the preceding conditions are true.
There are two syntaxes of the CASE statement: one equivalent to an if-else statement, and the other is structured like a switch statement. The if-else version evaluates the boolean condition within each WHEN-clause and executes the first block of statements whose condition is true. The optional concluding ELSE-clause is executed only if all WHEN-clause conditions are false.
The switch version evaluates the expression following the keyword WHEN and compares its value to the expression immediately following the keyword CASE. These expressions do not need to be boolean; the CASE statement compares pairs of expressions to see if their values are equal. The first WHEN-THEN clause to have an expression value equal to the CASE expression value is executed; the remaining clauses are skipped. The optional ELSE-clause is executed only if no WHEN-clause expression has a value matching the CASE value.
CASE Semantics
STRING drink ="Juice";# CASEstatement: if-elseversionCASEWHEN drink =="Juice"THEN @@calories +=50WHEN drink =="Soda"THEN @@calories +=120 ...ELSE @@calories =0 # Optional else-clauseEND# Since drink ="Juice", 50 will be added to calories# CASEstatement: switch versionCASE drink WHEN"Juice"THEN @@calories +=50WHEN"Soda"THEN @@calories +=120 ...ELSE @@calories =0 # Optional else-clauseEND# Since drink ="Juice", 50 will be added to calories
Example 1. CASE as IF-ELSE
# Display the total numbertimes connected users posted about a certain subjectCREATE QUERY userNetworkPosts (vertex<person> seedUser, STRING subjectName) FOR GRAPH socialNet { SumAccum<INT> @@topicSum =0; OrAccum @visited; reachableVertices = {}; # empty vertex set visitedVertices (ANY) = {seedUser}; # set that can contain ANY type of vertexWHILE visitedVertices.size() !=0 DO # loop terminates when all neighbors are visited visitedVertices =SELECT s # s is all neighbors of visitedVertices which have not been visitedFROM visitedVertices-(:e)->:sWHERE s.@visited == false ACCUM s.@visited = true,CASEWHEN s.type =="post"and s.subject == subjectName THEN @@topicSum +=1END;END;PRINT @@topicSum;}
# give each social network user a social impact score which accumulates# based on how many friends and posts they haveCREATE QUERY scoreSocialImpact() FOR GRAPH socialNet api("v2") { SumAccum<INT> @socialImpact =0; allPeople = {person.*}; people =SELECT v FROM allPeople:v ACCUM CASEWHEN v.outdegree("friend") >1THEN v.@socialImpact +=1END, # +1pointforhaving>1 friendCASEWHEN v.outdegree("friend") >2THEN v.@socialImpact +=1END, # +1pointforhaving>2 friendsCASEWHEN v.outdegree("posted") >1THEN v.@socialImpact +=1END, # +1pointforhaving>1 postsCASEWHEN v.outdegree("posted") >3THEN v.@socialImpact +=2END; # +2 points forhaving>2 posts#PRINT people.@socialImpact; // api v1PRINT people[people.@socialImpact]; // api v2}
# give each user post a rating based on the subjectand how many likes it hasCREATE QUERY ratePosts() FOR GRAPH socialNet api("v2") { SumAccum<INT> @rating =0; allPeople = {person.*}; results =SELECT v FROM allPeople -(:e)-> post:v ACCUM CASE e.typeWHEN"posted"THENCASEWHEN v.subject =="cats"THEN v.@rating +=-1 # -1if post about catsWHEN v.subject =="Graphs"THEN v.@rating +=2 # +2if post about graphsWHEN v.subject =="tigergraph"THEN v.@rating +=10 # +10if post about tigergraphENDWHEN"liked"THEN v.@rating +=3 # +3 each time post was likedEND;#PRINT results.@rating; // api v1PRINT results[results.@rating]; // api v2}
The WHILE statement provides unbounded iteration over a block of statements. WHILE statements can be used as query-body statements or DML-sub-statements. (See the note about differences in block syntax .)
WHILE syntax
queryBodyWhileStmt :=WHILE condition [LIMIT (name | integer)] DO queryBodyStmts ENDDMLSubWhileStmt :=WHILE condition [LIMIT (name | integer)] DO DMLSubStmtList END
The WHILE statement iterates over its body ( queryBodyStmts or DMLSubStmtList ) until the condition evaluates to false or until the iteration limit is met. A condition is any expression that evaluates to a boolean. The condition is evaluated before each iteration. CONTINUE statements can be used to change the control flow within the while block. BREAK statements can be used to exit the while loop.
A WHILE statement may have an optional LIMIT clause. LIMIT clauses has a constant positive integer value or integer variable to constrain the maximum number of loop iterations. The example below demonstrates how the LIMIT behaves.
If a limit value is not specified, it is possible for a WHILE loop to iterate infinitely. It is the responsibility of the query author to design the condition logic so that it is guaranteed to eventually be true (or to set a limit).
WHILE LIMIT semantics
# These three WHILE statements behave the same. Each terminates when# (v.size ==0) orafter5 iterations of the loop.WHILE v.size() !=0LIMIT5 DO # Some statements END;INT iter =0;WHILE (v.size() !=0) AND (iter <5) DO# Some statements iter = iter +1; END;INT iter =0;WHILE v.size() !=0 DOIF iter ==5THENBREAK; END;# Some statements iter = iter +1; END;
Below are a number of examples that demonstrate the use of WHILE statements.
Example 1. Simple WHILE loop
# find all vertices which are reachable from a starting seed vertex (i.e., breadth-first search)CREATE QUERY reachable(vertex<person> seed) FOR GRAPH workNet{ OrAccum @visited; reachableVertices = {}; # empty vertex set visitedVertices (ANY) = {seed}; # set that can contain ANY type of vertexWHILE visitedVertices.size() !=0 DO # loop terminates when all neighbors are visited visitedVertices =SELECT s # s is all neighbors of visitedVertices which have not been visitedFROM visitedVertices-(:e)->:sWHERE s.@visited == false POST-ACCUM s.@visited = true; reachableVertices = reachableVertices UNION visitedVertices;END;PRINT reachableVertices;}
# find all vertices which are reachable within two hops from a starting seed vertex (i.e., breadth-first search)CREATE QUERY reachableWithinTwo(vertex<person> seed) FOR GRAPH workNet{ OrAccum @visited; reachableVertices = {}; # empty vertex set visitedVertices (ANY) = {seed}; # set that can contain ANY type of vertex WHILE visitedVertices.size() !=0 LIMIT 2 DO # loop terminates when all neighbors within 2-hops of the seed vertex are visited
visitedVertices =SELECT s # s is all neighbors of visitedVertices which have not been visitedFROM visitedVertices-(:e)->:sWHERE s.@visited == false POST-ACCUM s.@visited = true; reachableVertices = reachableVertices UNION visitedVertices;END;PRINT reachableVertices;}
The FOREACH statement provides bounded iteration over a block of statements. FOREACH statements can be used as query-body statements or DML-sub-statements. (See the note about differences in block syntax .)
FOREACH syntax
queryBodyForEachStmt := FOREACH forEachControl DO queryBodyStmts ENDDMLSubForEachStmt := FOREACH forEachControl DO DMLSubStmtList ENDforEachControl := (name | "("name [, name]+")") IN setBagExpr | nameINRANGE"[" expr , expr"]" [".STEP(" expr ")"]
The formal syntax for forEachControl appears complex. It can be broken down into the following cases:
name IN setBagExpr
tuple IN setBagExpr
name IN RANGE [ expr, expr ]
name IN RANGE [ expr, expr ].STEP ( expr )
Note that setBagExpr includes container accumulators and explicit sets.
The FOREACH statement has the following restrictions:
In a DML-sub level FOREACH, it is never permissible to update the loop variable (the variable declared before IN, e.g., var in "FOREACH var IN setBagExpr").
In a query-body level FOREACH, in most cases it is not permissible to update the loop variable. The following exceptions apply:
If the iteration is over a ListAccum, its values can be updated.
If the iteration is over a MapAccum, its values can be updated, but its keys cannot.
If the iteration is over a set of vertices, it is not permissible to access (read or write) their vertex-attached accumulators.
A query-body-level FOREACH cannot iterate over a set or bag of constants. For example, FOREACH i in (1,2,3) is not supported. However, DML-sub FOREACH does support this.
FOREACH ... IN RANGE
The FOREACH statement has an optional RANGE clause RANGE[expr, expr], which can be used to define the iteration collection. Optionally, the range may specify a step size:
RANGE[expr, expr].STEP(expr)
Each expr must evaluate to an integer. Any of the integers may be negative, but the step expr may not be 0.
The clause RANGE[a,b].STEP(c) produces the sequence of integers from a to b, inclusive, with step size c. That is,
(a, a+c, a+2*c, a+3*c, ... a+k*c), where k = the largest integer such that |k*c| ≤ |b-a|.
If the .STEP method is not given, then the step size c = 1.
Nested FOREACH IN RANGE with MapAccum
CREATE QUERY foreachRangeEx() FOR GRAPH socialNet { ListAccum<INT> @@t;Start= {person.*}; FOREACH i INRANGE[0, 2] DO @@t += i; L =SELECTStartFROMStartWHERE Start.id =="person1" ACCUM FOREACH j INRANGE[0, i] DO @@t += jEND ;END;PRINT @@t;}
CREATE QUERY foreachRangeStep(INT a, INT b, INT c) FOR GRAPH minimalNet { ListAccum<INT> @@t; FOREACH i INRANGE[a,b].step(c) DO @@t += i;END;PRINT @@t;}
The step value can be positive for an ascending range or negative for a descending range. If the step has the wrong polarity, then the loop has zero iterations; that is, the exit condition is already satisfied.
# Count the number of companies whose country matches the provided stringCREATE QUERY companyCount(STRING countryName) FOR GRAPH workNet { ListAccum<STRING> @@companyList;INT countryCount;start= {ANY}; # start will have a set of all vertex types s =SELECT v FROMstart:v # get all verticesWHERE v.type =="company" # that have a type of "company" ACCUM @@companyList += v.country; # append the country attribute from all company vertices to the ListAccum# Iterate the ListAccum and compare each element to the countryName parameter FOREACH item in @@companyList DOIF item == countryName THEN countryCount = countryCount +1;END;END;PRINT countryCount;}
#Find all company person who live in a given countryCREATE QUERY employeesByCompany(STRING country) FOR GRAPH workNet { ListAccum<VERTEX<company>> @@companyList;start= {ANY};# Build a list of all company vertices# (these are vertex IDs only) s =SELECT v FROMstart:vWHERE v.type =="company" ACCUM @@companyList += v;# Use the vertex IDs as Seeds for vertex sets FOREACH item IN @@companyList DO companyItem = {item}; employees =SELECT t FROM companyItem -(worksFor)-> :tWHERE (t.locationId == country);PRINT employees;END;}
# Count the number of employees from a given country and list their idsCREATE QUERY employeeByCountry(STRING countryName) FOR GRAPH workNet { MapAccum <STRING, ListAccum<STRING>> @@employees;# start will have a set of all person type verticesstart= {person.*};# Build a map using person locationId as a keyand a list of strings to hold multiple person ids s =SELECT v FROMstart:v ACCUM @@employees += (v.locationId -> v.id);# Iterate the map using (key,value) pairs FOREACH (key,val) in @@employees DOIFkey== countryName THENPRINT val.size();# Nested foreach to iterate over the list of person ids FOREACH employee in val DOPRINT employee;END;# MapAccum keys are unique so we can BREAKout of the loopBREAK;END;END;}
# Show post topics liked by users and show total likes per topicCREATE QUERY topicLikes() FOR GRAPH socialNet { SetAccum<STRING> @@personPosts; SumAccum<INT> @postLikes; MapAccum<STRING,INT> @@likesByTopic;start= {person.*};# Find all user posts and generate a set of post topics# (set has no duplicates) posts =SELECT g FROMstart- (posted) -> :g ACCUM @@personPosts += g.subject;# Useset of topics to increment how many times a specfic# post is liked by other users likedPosts =SELECT f FROMstart- (liked) -> :f ACCUM FOREACH x in @@personPosts DOCASEWHEN (f.subject == x) THEN f.@postLikes +=1ENDEND# Aggregate all liked totals by topic POST-ACCUM @@likesByTopic += (f.subject -> f.@postLikes);# Display the number of likes per topicPRINT @@likesByTopic;}
#Show a summary of the number of friends all persons have by genderCREATE QUERY friendGender() FOR GRAPH socialNet { ListAccum<STRING> @friendGender; SumAccum<INT> @@maleGenderCount; SumAccum<INT> @@femaleGenderCount;start= {person.*};# Record a list showing each friend's gender socialMembers = SELECT s from start:s -(friend)-> :g ACCUM s.@friendGender += (g.gender) # Loop over each list of genders and total them POST-ACCUM FOREACH x in s.@friendGender DO CASE WHEN (x == "Male") THEN @@maleGenderCount += 1 ELSE @@femaleGenderCount += 1 END END; PRINT @@maleGenderCount; PRINT @@femaleGenderCount;}
The CONTINUE and BREAK statements can only be used within a block of a WHILE or FOREACH statement. The CONTINUE statement branches control flow to the end of the loop, skipping any remaining statements in the current iteration, and proceeding to the next iteration. That is, everything in the loop block after the CONTINUE statement will be skipped, and then the loop will continue as normal.
The BREAK statement branches control flow out of the loop, i.e., it will exit the loop and stop iteration.
Below are a number of examples that demonstrate the use of BREAK and CONTINUE.
Continue and Break Semantics
# Whilewith a continueINT i =0;INT nCount =0;WHILE i <10 DO i = i +1;IF (i % 2==0) { CONTINUE; } nCount = nCount +1;END;# i is10, nCount is5 (skips the increment for every even i).# Whilewith a breaki =0;WHILE i <10 DOIF (i ==5) { BREAK; } # When i is5 the loopis exited i = i +1;END;# i isnow5
Example 1. Break
# find posts of a given person, and post of friends of that person, friends of friends, etc# until a post about cats is found. The number of friend-hops to reach is the 'degree' of catsCREATE QUERY findDegreeOfCats(vertex<person> seed) FOR GRAPH socialNet{ SumAccum<INT> @@degree =0; OrAccum @@foundCatPost = false; OrAccum @visited = false; friends (ANY) = {seed};WHILE @@foundCatPost != true AND friends.size() >0 DO posts =SELECT v FROM friends-(posted:e)->:v ACCUM CASEWHEN v.subject =="cats"THEN @@foundCatPost += true END;IF @@foundCatPost THENBREAK;END; friends =SELECT v FROM friends-(friend:e)->:vWHERE v.@visited == false ACCUM v.@visited = true; @@degree +=1;END;PRINT @@degree;}
Example 2. findEnoughFriends.gsql: While loop using continue statement
# find all 3-hop friends of a starting vertex. count coworkers as friends# if there are not enough friendsCREATE QUERY findEnoughFriends(vertex<person> seed) FOR GRAPH friendNet{ SumAccum<INT> @@distance =0; # keep track of the distance from the seed OrAccum @visited = false; visitedVertices = {seed};WHILE true LIMIT3 DO @@distance +=1;# traverse from visitedVertices to its friends friends =SELECT vFROM visitedVertices -(friend:e)-> :vWHERE v.@visited == false POST-ACCUM v.@visited = true;PRINT @@distance, friends;# ifnumber of friends at this levelis sufficient, finish this iterationIF visitedVertices.size() >=2THEN visitedVertices = friends;CONTINUE;END;# if fewer than 4 friends, addin coworkers coworkers =SELECT vFROM visitedVertices -(coworker:e)-> :vWHERE v.@visited == false POST-ACCUM v.@visited = true; visitedVertices = friends UNION coworkers;PRINT @@distance, coworkers;END;}
# find at least the top-k companies closest to a given seed vertex, if they existCREATE QUERY topkCompanies(vertex<person> seed, INT k) FOR GRAPH workNet{ SetAccum<vertex<company>> @@companyList; OrAccum @visited = false; visitedVertices (ANY) = {seed};WHILE true DO visitedVertices =SELECT v # traverse from x to its unvisited neighborsFROM visitedVertices -(:e)-> :vWHERE v.@visited == false ACCUM CASEWHEN (v.type =="company") THEN # count the number of company vertices encountered @@companyList += vEND POST-ACCUM v.@visited += true; # mark vertices as visited# exit loopwhenat least k companies have been countedIF @@companyList.size() >= k OR visitedVertices.size() ==0THENBREAK;END;END;PRINT @@companyList;}
#List out all companies from a given countryCREATE QUERY companyByCountry(STRING countryName) FOR GRAPH workNet { MapAccum <STRING, ListAccum<STRING>> @@companies;start= {company.*}; # start will have a set of all company type vertices#Build a map using company country as a keyand a list of strings to hold multiple company ids s =SELECT v FROMstart:v ACCUM @@companies += (v.country -> v.id);#Iterate the map using (key,value) pairs FOREACH (key,val) IN @@companies DOIFkey!= countryName THENCONTINUE;END;PRINT val.size();#Nested foreach to iterate over the list of company ids FOREACH comp IN val DOPRINT comp;END;END;}
#List all the persons located in the specified country
CREATE QUERY employmentByCountry(STRING countryName) FOR GRAPH workNet {
MapAccum < STRING, ListAccum<STRING> > @@employees;
start = {person.*}; # start will have a set of all person type vertices
#Build a map using person locationId as a key and a list of strings to hold multiple person ids
s = SELECT v FROM start:v
ACCUM @@employees += (v.locationId -> v.id);
#Iterate the map using (key,value) pairs
FOREACH (key,val) IN @@employees DO
IF key == countryName THEN
PRINT val.size();
#Nested foreach to iterate over the list of person ids
FOREACH employee IN val DO
PRINT employee;
END;
BREAK;
END;
END;
}