Declaration and Assignment Statements
In GSQL, different types of variables and objects follow different rules when it comes to variable declaration and assignment. This section discusses the different types of declaration and assignment statements and covers the following subset of the EBNF syntax:
EBNF
1
## Declarations ##
2
accumDeclStmt :=
3
accumType localAccumName ["=" constant]
4
["," localASccumName ["=" constant]]*
5
| [STATIC] accumType globaAccumName ["=" constant]
6
["," GlobalAccumName ["=" constant]]*
7
localAccumName := "@"accumName;
8
globalAccumName := "@@"accumName;
9
10
baseDeclStmt := baseType name ["=" constant] ["," name ["=" constant]]*
11
fileDeclStmt := FILE fileVar "(" filePath ")"
12
fileVar := name
13
14
localVarDeclStmt := baseType varName "=" expr
15
16
vSetVarDeclStmt := vertexSetName ["(" vertexType ")"] "=" (seedSet | simpleSet | selectBlock)
17
18
simpleSet := vertexSetName
19
| "(" simpleSet ")"
20
| simpleSet (UNION | INTERSECT | MINUS) simpleSet
21
22
seedSet := "{" [seed ["," seed ]*] "}"
23
seed := '_'
24
| ANY
25
| vertexSetName
26
| globalAccumName
27
| vertexType ".*"
28
| paramName
29
| "SelectVertex" selectVertParams
30
31
selectVertParams := "(" filePath "," columnId "," (columnId | name) ","
32
stringLiteral "," (TRUE | FALSE) ")" ["." FILTER "(" condition ")"]
33
34
columnId := "quot; (integer | stringLiteral)
35
36
## Assignment Statements ##
37
assignStmt := name "=" expr
38
| name "." attrName "=" expr
39
40
attrAccumStmt := name "." attrName "+=" expr
41
42
lAccumAssignStmt := vertexAlias "." localAccumName ("+="| "=") expr
43
44
gAccumAssignStmt := globalAccumName ("+=" | "=") expr
45
46
loadAccumStmt := globalAccumName "=" "{" LOADACCUM loadAccumParams
47
["," LOADACCUM loadAccumParams]* "}"
48
49
loadAccumParams := "(" filePath "," columnId ["," columnId]* ","
50
stringLiteral "," (TRUE | FALSE) ")" ["." FILTER "(" condition ")"]
51
52
## Function Call Statement ##
53
funcCallStmt := name ["<" type ["," type]* ">"] "(" [argList] ")"
54
| globaAccumName ("." funcName "(" [argList] ")")+
55
| "reset_collection_accum" "(" accumName ")"
56
57
argList := expr ["," expr]*
Copied!

Variable scopes

Different types of variable declarations use different scoping rules. There are two types of scoping rules in a GSQL query:

Block scoping

In GSQL, curly brackets, as well as IF .. THEN, ELSE, WHILE ... DO, FOREACH ... DO statements create a block. A SELECT statement also creates a block. A block-scoped variable declared inside a block scope is only accessible inside that scope.
Additionally, variables declared in a lower scope can use the same name as a variable already declared in a higher scope. The lower-scope declaration will take precedence over the higher-scope declaration until the end of the lower scope.
The following types of variables use block scoping:

Global scoping

A global-scoped variable is always accessible anywhere in the query once it has been declared regardless of where it is declared. One also cannot declare another variable with the same name as a global-scoped variable that has already been declared.
The following types of variables use global scoping:

Declaration Statements

There are six types of variable declarations in a GSQL query:
  • Accumulator
  • Base type variable
  • Local base type variable
  • Vertex set
  • File object
  • Vertex or edge aliases
The first five types each have their own declaration statement syntax and are covered in this section. Aliases are declared implicitly in a SELECT statement.

Accumulators

Accumulator declaration is discussed in Accumulators.

Base type variables

In a GSQL query body, variables holding values of types INT, UINT, FLOAT, DOUBLE, BOOL, STRING, DATETIME, VERTEX, EDGE, JSONOBJECT and JSONARRAY are called base type variables. The scope of a base type variable is from the point of declaration until the end of the block where its declaration took place.
EBNF for base type variable declaration
1
baseVarDeclStmt := baseType name ["=" expr]["," name ["=" expr]]*
Copied!
A base type variable can be declared and accessed anywhere in the query. To declare a base type variable, specify the data type and the variable name. Optionally, you can initialize the variable by assigning it a value with the assignment operator (=) and the desired value on the right side. You can declare multiple variables of the same type in a single declaration statement.
1
CREATE QUERY baseTypeVariable() {
2
STRING a;
3
DOUBLE num1, num2 = 3.2;
4
INT year = 2020, month = 12, day = 115;
5
INT b = rand(5);
6
PRINT a, b, num;
7
}
Copied!
When a base type variable is assigned a new value in an ACCUM or POST-ACCUM clause, the change will not take place until exitng the clause. Therefore, if there are multiple assignment statements for the same base type variable in an ACCUM or POST-ACCUM clause, only the last one will take effect.
For example, in the following query, a base type variable is assigned a new value in the ACCUM clause, but the change will not take place until the clause ends. Therefore, the accumulator will not receive the value and will hold a value of 0 at the end of the query.
1
CREATE QUERY baseTypeVariable(vertex<person> m1) FOR GRAPH socialNet {
2
MaxAccum<INT> @@maxDateGlob;
3
DATETIME dt;
4
5
allUser = {person.*};
6
allUser = SELECT src
7
FROM allUser:src - (liked:e) -> post
8
ACCUM
9
dt = e.actionTime, # dt isn't updated yet
10
@@maxDateGlob += datetime_to_epoch(dt);
11
PRINT @@maxDateGlob, dt; # @@maxDateGlob will be 0
12
}
Copied!

Local base type variables

Base type variables declared in a DML-sub statement, such as in a statement inside a ACCUM, POST-ACCUM, or UPDATE SET clause, are called local base type variables.
Local base type variables are block-scoped and are accessible in the block where they are declared only. Within a local base type variable's scope, another local base type variable with the same name cannot be declared at the same level. However, a new local base type variable with the same name can be declared at a lower level (i.e., within a nested SELECT or UPDATE statement). The lower declaration takes precedence at the lower level.
In a POST-ACCUM clause, each local base type variable may only be used in source vertex statements or only in target vertex statements, not both.
EBNF for local base type variable declaration and initialization
1
localVarDeclStmt := baseType varName "=" expr
Copied!
Local base type variables are not subject to the assignment restrictions of regular base type variables. Their values can be updated inside an ACCUM or POST-ACCUM clause and the change will take place immediately.

Example:

Base type variable declaration in DML statements
1
# An example showing a local base type variable succeeds
2
# where a base type variable fails
3
CREATE QUERY localVariable(vertex<person> m1) FOR GRAPH socialNet {
4
MaxAccum<INT> @@maxDate, @@maxDateGlob;
5
DATETIME dtGlob;
6
7
allUser = {person.*};
8
allUser = SELECT src
9
FROM allUser:src - (liked:e) -> post
10
ACCUM
11
DATETIME dt = e.actionTime, # Declare and assign local dt
12
dtGlob = e.actionTime, # dtGlob isn't updated yet
13
@@maxDate += datetime_to_epoch(dt),
14
@@maxDateGlob += datetime_to_epoch(dtGlob);
15
PRINT @@maxDate, @@maxDateGlob, dtGlob; # @@maxDateGlob will be 0
16
}
Copied!
localVariable Query Results
1
GSQL > RUN QUERY localVariable("person1")
2
{
3
"error": false,
4
"message": "",
5
"version": {
6
"edition": "developer",
7
"schema": 0,
8
"api": "v2"
9
},
10
"results": [{
11
"dtGlob": "2010-01-11 03:26:05",
12
"@@maxDateGlob": 0,
13
"@@maxDate": 1263618953
14
}]
15
}
Copied!

Vertex Set Variable Declaration and Assignment

Variables that contain a set of one or more vertices are called vertex set variables. Vertex set variables play a special role within GSQL queries. They are used for both the input and output of SELECT statements. Therefore, before the first SELECT statement in a query, a vertex set variable must be declared and initialized. This initial vertex set is called the seed set.
Vertex set variables are global-scoped. They are also the only type of variable that isn't explicitly typed during declaration. To declare a vertex set variable, assign an initial set of vertices to the variable name.
EBNF for Vertex Set Variable Declaration
1
vSetVarDeclStmt := vertexSetName ["(" vertexType ")"] "=" (seedSet | simpleSet | selectBlock)
2
3
simpleSet := vertexSetName
4
| "(" simpleSet ")"
5
| simpleSet (UNION | INTERSECT | MINUS) simpleSet
6
7
seedSet := "{" [seed ["," seed ]*] "}"
8
seed := '_'
9
| ANY
10
| vertexSetName
11
| globalAccumName
12
| vertexType ".*"
13
| paramName
14
| "SelectVertex" selectVertParams
15
16
selectVertParams := "(" filePath "," columnId "," (columnId | name) ","
17
stringLiteral "," (TRUE | FALSE) ")" ["." FILTER "(" condition ")"]
18
19
columnId := "quot; (integer | stringLiteral)
Copied!
The query below lists all ways of assigning a vertex set variable an initial set of vertices (that is, forming a seed set).
  • A vertex parameter, untyped or typed, enclosed in curly brackets
  • A vertex set parameter, untyped or typed
  • A global SetAccum<VERTEX> accumulator, untyped or typed
  • All vertices of any type or of one type
  • A list of vertex IDs in an external file
  • Copy of another vertex set
  • A combination of individual vertices, vertex set parameters, or base type variables, enclosed in curly brackets
  • Union of vertex set variables
Seed Set Example
1
CREATE QUERY seedSetExample(VERTEX v1, VERTEX<person> v2, SET<VERTEX> v3, SET<VERTEX<person>> v4) FOR GRAPH socialNet {
2
SetAccum<VERTEX> @@testSet;
3
SetAccum<VERTEX<person>> @@testSet2;
4
S1 = { v1 }; # untyped vertex parameter enclosed in curly brackets
5
S2 = { v2 }; # typed vertex parameter enclosed in curly brackets
6
S3 = v3; # untyped vertex set parameter
7
S4 = v4; # typed vertex set parameter
8
S5 = @@testSet; # untyped global set accumulator
9
S6 = @@testSet2; # typed global set accumulator
10
S7 = ANY; # All vertices
11
S8 = person.*; # All person vertices
12
S9 = _; # Equivalent to ANY
13
S10 = SelectVertex("absolute_path_to_input_file", $0, post, ",", false); # See Section "SelectVertex()" function
14
S11 = S1; # copy of another vertex set
15
S12 = {@@testSet, v2, v3}; # Individual vertex: v2
16
# Vertex set parameter: v3
17
# global accumulator: @@testSet
18
# Inside curly brackets cannot be put another
19
# seedset, e.g., S1
20
S13 = S11 UNION S12; # but we can use UNION to combine S1
21
}
Copied!
When declaring a vertex set variable, a set of vertex types can be optionally specified to the vertex set variable. If the vertex set variable set type is not specified explicitly, the system determines the type implicitly by the vertex set value. The type can be ANY, _ (equivalent to ANY), or any explicit vertex type(s). See the EBNF grammar rule vertexEdgeType.
Declaration syntax difference: vertex set variable vs. base type variable
In a vertex set variable declaration, the optional type specifier follows the variable name and should be surrounded by parentheses: vSetName(type) This is different than a base type variable declaration, where the type specifier is required and comes before the base variable name: type varName

Assignment

After a vertex set variable is declared, the vertex type of the vertex set variable is immutable. Every assignment (e.g. SELECT statement) to this vertex set variable must match the type. The following is an example in which we must declare the vertex set variable type.
Vertex set variable type
1
CREATE QUERY vertexSetVariableTypeExample(vertex<person> m1) FOR GRAPH socialNet {
2
INT ite = 0;
3
S (ANY) = {m1}; # ANY is necessary
4
WHILE ite < 5 DO
5
S = SELECT t
6
FROM S:s - (ANY:e) -> ANY:t;
7
8
ite = ite + 1;
9
END;
10
PRINT S;
11
}
Copied!
In the above example, the query returns the set of vertices after a 5-step traversal from the input person vertex. If we declare the vertex set variable S without explicitly giving a type, because the type of vertex parameter m1 is person, the GSQL engine will implicitly assign S to be person type. However, if S is assigned to person type, the SELECT statement inside the WHILE loop causes a type-checking error, because the SELECT block will generate all connected vertices, including non-person vertices. Therefore, S must be declared as an ANY-type vertex set variable.

FILE Object Declaration

A FILE object is a sequential text storage object, associated with a text file on the local machine.
EBNF for FILE object declaration
1
fileDeclStmt := FILE fileVar "(" filePath ")"
2
fileVar := name
Copied!
When a FILE object is declared, associated with a particular text file, any existing content in the text file will be erased. During the execution of the query, content written to or printed to the FILE object will be appended to the FILE object. When the query where the FILE object is declared finishes running, the content of the FILE object is saved to the text file.

Example:

File object query example
1
CREATE QUERY getUSWorkerInterests (STRING fileLocation) FOR GRAPH workNet {
2
// Declare FILE object f1
3
FILE f1 (fileLocation);
4
// Initialize a seed set of all person vertices
5
P = {person.*};
6
7
PRINT "header" TO_CSV f1;
8
9
// Select workers located in the US and print their interests onto
10
// the FILE object
11
USWorkers = SELECT v FROM P:v
12
WHERE v.locationId == "us"
13
ACCUM f1.println(v.id, v.interestList);
14
PRINT "footer" TO_CSV f1;
15
}
16
INSTALL QUERY getUSWorkers
17
RUN QUERY getUSWorkerInterests("/home/tigergraph/fileEx.txt")
Copied!

Assignment and Accumulate Statements

Assignment statements are used to set or update the value of a variable after it has been declared. This applies to base type variables, vertex set variables, and accumulators. Accumulators also have the special += accumulate statement, which was discussed in the Accumulator section. Assignment statements can use expressions to define the new value of the variable.
EBNF for Assignment Statements
1
## Assignment Statement ##
2
assignStmt := name "=" expr # baseType variable, vertex set variable
3
| name "." name "=" expr # attribute of a vertex or edge
4
5
attrAccumStmt := name "." attrName "+=" expr
6
7
lAccumAssignStmt := vertexAlias "." localAccumName ("+="| "=") expr
8
9
gAccumAssignStmt := globalAccumName ("+=" | "=") expr
10
11
loadAccumStmt := globalAccumName "=" "{" "LOADACCUM" loadAccumParam
12
["," "LOADACCUM" loadAccumParams]* "}"
Copied!
Vertex and edge (non-accumulator) attributes can use the += operator in an ACCUM or POST-ACCUM clause to perform parallel accumulation.
1
attrAccumStmt := name "."attrName "+=" expr
Copied!

Restrictions on Assignment Statements

In general, assignment statements can take place anywhere after the variable has been declared. However, there are some restrictions. These restrictions apply to "inner level" statements which are within the body of a higher-level statement:
  • The ACCUM or POST-ACCUM clause of a SELECT statement
  • The SET clause of an UPDATE statement
  • The body of a FOREACH statement
  • Global accumulator assignment is not permitted within the body of SELECT or UPDATE statements
  • Base type variable assignment is permitted in ACCUM or POST-ACCUM clauses, but the change in value will not take place until exiting the clause. Therefore, if there are multiple assignment statements for the same variable, only the final one will take effect.
  • Vertex attribute assignment is not permitted in an ACCUM clause. However, edge attribute assignment is permitted. This is because the ACCUM clause iterates over an edge set.
  • There are additional restrictions within FOREACH loops for the loop variable. See the Data Modification section.

LOADACCUM Statement

1
loadAccumStmt := globalAccumName "=" "{" LOADACCUM loadAccumParams
2
["," LOADACCUM loadAccumParams]* "}"
3
4
loadAccumParams := "(" filePath "," columnId ["," [columnId]* ","
5
stringLiteral "," (TRUE | FALSE) ")" ["."FILTER "(" condition ")"]
6
columnId := "quot;(integer | stringLiteral)
Copied!
LOADACCUM() can initialize a global accumulator by loading data from a file. LOADACCUM() has 3+n parameters explained in the table below, where n is the number of fields in the accumulator.
Any accumulator using generic VERTEX as an element type cannot be initialized by LOADACCUM().

Parameters:

Name
Type
Description
filePath
String
The absolute file path of the input file to be read. A relative path is not supported.
columnId
String or number
The column position(s) or column name(s) of the data file that supply data values to each field of the accumulator.
separator
Single-character string
The separator of columns.
header
Boolean
Whether this file has a header.
One assignment statement can have multiple LOADACCUM() function calls. However, every LOADACCUM() referring to the same file in the same assignment statement must use the same separator and header parameter values.

Example:

loadAccumInput.csv
1
person1,1,"test1",3
2
person5,2,"test2",4
3
person6,3,"test3",5
Copied!
LoadAccum example
1
CREATE QUERY loadAccumEx(STRING filename) FOR GRAPH socialNet {
2
TYPEDEF TUPLE<STRING aaa, VERTEX<post> ddd> yourTuple;
3
MapAccum<VERTEX<person>, MapAccum<INT, yourTuple>> @@testMap;
4
GroupByAccum<STRING a, STRING b, MapAccum<STRING, STRING> strList> @@testGroupBy;
5
6
@@testMap = { LOADACCUM (filename, $0, $1, $2, $3, ",", false)};
7
@@testGroupBy = { LOADACCUM ( filename, $1, $2, $3, $3, ",", true) };
8
9
PRINT @@testMap, @@testGroupBy;
10
}
Copied!
Results of Query loadAccumEx
1
GSQL > RUN QUERY loadAccumEx("/file_directory/loadAccumInput.csv")
2
{
3
"error": false,
4
"message": "",
5
"version": {
6
"edition": "developer",
7
"schema": 0,
8
"api": "v2"
9
},
10
"results": [{
11
"@@testGroupBy": [
12
{
13
"a": "3",
14
"b": "\"test3\"",
15
"strList": {"5": "5"}
16
},
17
{
18
"a": "2",
19
"b": "\"test2\"",
20
"strList": {"4": "4"}
21
}
22
],
23
"@@testMap": {
24
"person1": {"1": {
25
"aaa": "\"test1\"",
26
"ddd": "3"
27
}},
28
"person6": {"3": {
29
"aaa": "\"test3\"",
30
"ddd": "5"
31
}},
32
"person5": {"2": {
33
"aaa": "\"test2\"",
34
"ddd": "4"
35
}}
36
}
37
}]
38
}
Copied!

Function Call Statements

1
funcCallStmt := name ["<" type ["," type]* ">"] "(" [argList] ")"
2
| globalAccumName ("." funcName "(" [argList] ")")+
3
| "reset_collection_accum" "(" accumName ")"
4
5
argList := expr ["," expr]*
Copied!
Typically, a function call returns a value and so is part of an expression. In some cases, however, the function does not return a value (i.e., returns VOID) or the return value can be ignored, so the function call can be used as an entire statement. This is a Function Call Statement.
Examples of Function Call statements
1
ListAccum<STRING> @@listAcc;
2
BagAccum<INT> @@bagAcc;
3
...
4
# examples of function call statements
5
@@listAcc.clear();
6
@@bagAcc.removeAll(0);
Copied!

Clear Collection Accumulators

Collection accumulators (e.g., ListAccum, SetAccum, MapAccum) grow in size as data is added. Particularly for vertex-attached accumulators, if the number of vertices is large, their memory consumption can be significant. It can improve system performance to clear or reset collection accumulators during a query as soon as their data is no longer needed. Running the reset_collection_accum(accumName) function resets the collection(s) to be zero-length (empty). If the argument is a vertex-attached accumulator, then the entire set of accumulators is reset.
1
"reset_collection_accum" "(" accumName ")"
Copied!
reset_collection_accum only works in DISTRIBUTED mode queries. If the query is not in distributed mode, the reset does not take place.
1
CREATE DISTRIBUTED QUERY reset_accum()
2
FOR GRAPH workNet SYNTAX v2 {
3
ListAccum<STRING> @stuff;
4
ListAccum<STRING> @@allStuff;
5
6
Comp = SELECT c
7
FROM person:p -(worksFor:w)- company:c
8
ACCUM c.@stuff += p.id,
9
@@allStuff += p.id,
10
c.@stuff += p.locationId,
11
@@allStuff += p.locationId,
12
FOREACH interest IN p.interestList DO
13
c.@stuff += interest,
14
@@allStuff += interest
15
END
16
;
17
// display accum size: should be full
18
PRINT Comp[Comp.@stuff.size()] AS stuffCount;
19
PRINT @@allStuff.size() AS allStuffCount;
20
21
reset_collection_accum(@stuff);
22
reset_collection_accum(@@allStuff);
23
// display accum size: should be empty
24
PRINT Comp[Comp.@stuff.size()] AS stuffClear;
25
PRINT @@allStuff.size() AS allStuffClear;
26
}
Copied!
1
[{
2
"stuffCount": [
3
{"attributes": {"[email protected]()": 23},
4
"v_id": "company2",
5
"v_type": "company"
6
},
7
{"attributes": {"[email protected]()": 7},
8
"v_id": "company4",
9
"v_type": "company"
10
},
11
{"attributes": {"[email protected]()": 12},
12
"v_id": "company3",
13
"v_type": "company"
14
},
15
{"attributes": {"[email protected]()": 21},
16
"v_id": "company1",
17
"v_type": "company"
18
},
19
{"attributes": {"[email protected]()": 4},
20
"v_id": "company5",
21
"v_type": "company"
22
}]
23
},
24
{
25
"allStuffCount": 67
26
},
27
{
28
"stuffClear": [
29
{"attributes": {"[email protected]()": 0},
30
"v_id": "company2",
31
"v_type": "company"
32
},
33
{"attributes": {"[email protected]()": 0},
34
"v_id": "company4",
35
"v_type": "company"
36
},
37
{"attributes": {"[email protected]()": 0},
38
"v_id": "company3",
39
"v_type": "company"
40
},
41
{"attributes": {"[email protected]()": 0},
42
"v_id": "company1",
43
"v_type": "company"
44
},
45
{"attributes": {"[email protected]()": 0},
46
"v_id": "company5",
47
"v_type": "company"
48
}]
49
},
50
{
51
"allStuffClear": 0
52
}]
Copied!