Output Statements and FILE Objects

PRINT Statement (API v2)

The PRINT statement specifies output data. Each execution of a PRINT statement adds a JSON object to the results array which will be part of the query output. A PRINT statement can appear anywhere that query-body statements are permitted.
A PRINT statement does not trigger immediate output. The full set of data from all PRINT statements is delivered at one time, when the query concludes.
A query can print a maximum of 2GB of data.
If the output is to a FILE object, then the size limit does not apply.
EBNF
1
printStmt := PRINT printExpr ("," printExpr)* [WHERE condition] [TO_CSV (filePath | fileVar)]
2
printExpr := (expr | vExprSet) [ AS jsonKey]
3
| tableName
4
vExprSet := expr "[" vSetProj ("," vSetProj)* "]"
5
vSetProj := expr [ AS jsonKey]
6
jsonKey := name
Copied!
Each PRINT statement contains a list of expressions for output data. The optional WHERE clause filters the output. If the condition is false for any items, then those items are excluded from the output.
Each printExpr contributes one key-value pair to the PRINT statement's JSON object result. The optional AS clause sets the JSON key for the expression, overriding the default key (explained below).
If the query includes one more tabular SELECT statements, the PRINT statement can include table names. Both tabular and non-tabular printExpr expressions can be including in one PRINT statement.
Simple Example Showing JSON Output Format
1
STRING str = "first statement";
2
INT number = 5;
3
PRINT str, number;
4
5
str = "second statement";
6
number = number + 1;
7
PRINT str, number;
8
9
# The statements above produce the following output
10
{
11
"version": {"edition": "developer","api": "v2","schema": 0},
12
"error": false,
13
"message": "",
14
"results": [
15
{
16
"str": "first statement",
17
"number": 5
18
},
19
{
20
"str": "second statement",
21
"number": 6
22
}
23
]
24
}
Copied!
Each printExpr may be one of the following:
  • A literal value
  • A global or local variable (including VERTEX and EDGE variables)
  • An attribute of a vertex variable, e.g., Person.name
  • A global accumulator
  • An expression whose terms are among the types above. The following operators may be used:
Data type
Operators
String
concatenation: +
Set
UNION INTERSECT MINUS
Numeric
Arithmetic: + - * / . % Bit: << >> & |
Parentheses can be used for controlling order of precedence.
  1. 1.
    A vertex set variable
  2. 2.
    A vertex expression set vExprSet (only available if the output API is set to "v2". Vertex expression sets are explained in a separate section below.

JSON Format: Keys

If a printExpr includes the optional AS name clause, then the name sets the key for that expression in the JSON output. Otherwise, the following rules determine the key: If the expression is simply a single variable (local variable, global variable, global accumulator, or vertex set variable), then the key is the variable name. Also, for a vertex expression set, the key is the vertex set variable name. Otherwise, the key is the entire expression, represented as a string.

JSON Format: Values

Each data type has a distinct output format.
  • Simple numeric, string, and boolean data types follow JSON standards.
  • Lists, sets, bags, and arrays are printed as JSON arrays (i.e., a list enclosed in square brackets).
  • Maps and tuples are printed as JSON objects (i.e., a list of key:value pairs enclosed in curly braces).
  • Vertices and edges have a custom JSON object, shown below.
  • A vertex set variable is treated as a list of vertices.
  • Accumulator output format is determined by the accumulator's return type. For example, an AvgAccum outputs a DOUBLE value, and a BitwiseAndAccum outputs an INT value. For container accumulators, simply consider whether the output is a list, set, bag, or map.
    • ListAccum, SetAccum, BagAccum, ArrayAccum: list
    • MapAccum: map
    • HeapAccum, GroupByAccum: list of tuples
Full details of vertices are printed only when part of a vertex set variable or vertex expression set. When a single vertex is printed (from a variable or accumulator whose data type happens to be VERTEX), only the vertex id is printed.
Cases where only the vertex id will be printed
1
ListAccum<VERTEX> @@vList; // not a vertex set variable
2
VERTEX v; // not a vertex set variable
3
...
4
PRINT @@vList, v; // output will contain only vertex ids
Copied!
Vertex (when not part of a vertex set variable)
The output is just the vertex id as a string:
Output Format for a Value which is a Vertex, not part of a Vertex Set Variable
1
"<vertex_id>"
Copied!
Vertex (as part of a vertex set variable)
Output Format for a Vertex as part of a Vertex Set Variable
1
{
2
"v_id": "<vertex_id>",
3
"v_type": "<vertex_type>",
4
"attributes": {
5
<list of key:value pairs,
6
one for each attribute
7
or vertex-attached accumulator>
8
}
9
}
Copied!
Edge
Output Format for a Value which is an Edge
1
{
2
"e_type": "<edge_type>",
3
"directed": <boolean_value>,
4
"from_id": "<source_vertex_id>",
5
"from_type": "<source_vertex_type>",
6
"to_id": "<target_vertex_id>",
7
"to_type": "<target_vertex_type>",
8
"attributes": {
9
<list of key:value pairs,
10
one for each attribute>
11
}
12
}
Copied!
List, Set or Bag
Output format for a Value which is a List, Set, or Bag
1
[
2
<value1>,
3
<value2>,
4
...,
5
<valueN>
6
]
Copied!
Map
Output Format for a Value which is a Map
1
{
2
<key1>: <value1>,
3
<key2>: <value2>,
4
...,
5
<keyN>: <valueN>
6
}
Copied!
Tuple
Output Format for a Value which is a Tuple
1
{
2
<fieldName1>: <value1>,
3
<fieldName2>: <value2>,
4
...,
5
<fieldNameN>: <valueN>
6
}
Copied!
Vertex Set Variable
Output Format for a Value which is a Vertex Set Variable
1
[
2
<vertex1>,
3
<vertex2>,
4
...,
5
<vertexN>
6
]
Copied!

Vertex Expression Set

A vertex expression set is a list of expressions which is applied to each vertex in a vertex set variable. The expression list is used to compute an alternative set of values to display in the "attributes" field of each vertex.
The easiest way to understand this is to consider examples containing only one term and then consider combinations. Consider the following example query. C is a vertex set variable containing the set of all company vertices. Furthermore, each vertex has a vertex-attached accumulator @count.
Example Query for Vertex Expression Set
1
# CREATE VERTEX company(PRIMARY_ID clientId STRING, id STRING, country STRING)
2
3
CREATE QUERY vExprSet () FOR GRAPH workNet {
4
SumAccum<INT> @count;
5
C = {company.*};
6
7
# include some print statements here
8
}
Copied!
If we print the full vertex set, the "attributes" field of each vertex will contain 3 fields: "id", "country", and "@count". Now consider some simple vertex expression sets:
  • PRINT C[C.country] prints the vertex set variable C, except that the "attributes" field will contain only "country", instead of 3 fields.
  • PRINT C[[email protected]] prints the vertex set variable C, except that the "attributes" field will contain only "@count", instead of 3 fields.
  • PRINT C[[email protected] AS company_count] prints the same as above, except that the "@count" accumulator is is aliased as "company_count".
  • PRINT C[C.id, [email protected]] prints the vertex set variable C, except that the "attributes" field will contain only "id" and "@count".
  • PRINT C[C.id+"_ex", [email protected]+1] prints the vertex set variable C, except that the "attributes" field contains the following:
    • One field consists of each vertex's id value, with the string "_ex" appended to it.
    • Another field consists of the @count value incremented by 1. Note: the value of @count itself has not changed, only the displayed value is incremented.
The last example illustrates the general format for a vertex expression set:
Syntax for Vertex Expression Set
1
vExprSet := expr "[" vSetProj {, vSetProj} "]"
2
vSetProj := expr [ AS name]
Copied!
The vertex expression set begins with the name of a vertex set variable. It is followed by a list of attribute expressions, enclosed in square brackets. Each attribute expression follows the same rules described earlier in the Print Expressions section. That is, each attribute expression may refer to one or more attributes or vertex-attached accumulators of the current vertices, as well as literals, local or global variables, and global accumulators. The allowed operators (for numeric, string, or set operations) are the same ones mentioned above.
The key for the vertex expression set is the vertex set variable name.
The value for the vertex expression set is a modified vertex set variable, where the regular "attributes" value for each vertex is replaced with a set of key:value pairs corresponding to the set of attribute expressions given in the print expression.
An example which shows all of the cases described above, in combination, is shown below.
Print Basic Example
1
CREATE QUERY printExampleV2(VERTEX<person> v) FOR GRAPH socialNet {
2
3
SetAccum<VERTEX> @@setOfVertices;
4
SetAccum<EDGE> @postedSet;
5
MapAccum<VERTEX,ListAccum<VERTEX>> @@testMap;
6
FLOAT paperWidth = 8.5;
7
INT paperHeight = 11;
8
STRING Alpha = "ABC";
9
10
Seed = person.*;
11
A = SELECT s
12
FROM Seed:s
13
WHERE s.gender == "Female"
14
ACCUM @@setOfVertices += s;
15
16
B = SELECT t
17
FROM Seed:s - (posted:e) -> post:t
18
ACCUM s.@postedSet += e,
19
@@testMap += (s -> t);
20
21
# Numeric, String, and Boolean expressions, with renamed keys:
22
PRINT paperHeight*paperWidth AS PaperSize, Alpha+"XYZ" AS Letters,
23
A.size() > 10 AS AsizeMoreThan10;
24
# Note how an expression is named if "AS" is not used:
25
PRINT A.size() > 10;
26
27
# Vertex variables. Only the vertex id is included (no attributes):
28
PRINT v, @@setOfVertices;
29
30
# Map of Person -> Posts posted by that person:
31
PRINT @@testMap;
32
33
# Vertex Set Variable. Each vertex has a vertex-attached accumulator, which
34
# happens to be a set of edges (SetAccum<EDGE>), so edge format is shown also:
35
PRINT A AS VSetVarWomen;
36
37
# Vertex Set Expression. The same set of vertices as above, but with only
38
# one attribute plus one computed attribute:
39
PRINT A[A.gender, A.@postedSet.size()] AS VSetExpr;
40
}
Copied!
Note how the results of the six PRINT statements are grouped in the JSON "results" field below:
  1. 1.
    Each of the six PRINT statements is represented as one JSON object with the "results" array.
  2. 2.
    When a PRINT statement has more than one expression (like the first one), the expressions may appear in the output in a different order than on the PRINT statement.
  3. 3.
    The 2nd PRINT statement shows a key that is generated from the expression itself.
  4. 4.
    The 3rd and 4th PRINT statements show a set of vertices (different than a vertex set variable) and a map, respectively.
  5. 5.
    The 5th PRINT statement shows the vertex set variable A, including its vertex-attached accumulators (PRINT A).
  6. 6.
    The 6th PRINT statement shows a vertex set expression for A, customized to include only one static attribute plus a newly computed attribute.
Results from Query printExampleV2 (WITH COMMENTS ADDED)
1
GSQL > RUN QUERY printExampleV2("person1")
2
{
3
"error": false,
4
"message": "",
5
"version": {
6
"edition": "developer",
7
"schema": 0,
8
"api": "v2"
9
},
10
"results": [
11
{
12
"AsizeMoreThan10": false,
13
"Letters": "ABCXYZ",
14
"PaperSize": 93.5
15
},
16
{"A.size()>10": false},
17
{
18
"v": "person1",
19
"@@setOfVertices": [ "person4", "person5", "person2" ]
20
},
21
{"@@testMap": {
22
"person4": ["3"],
23
"person3": ["2"],
24
"person2": ["1"],
25
"person1": ["0"],
26
"person8": [ "7", "8" ],
27
"person7": [ "9", "6" ],
28
"person6": [ "10", "5" ],
29
"person5": [ "4", "11" ]
30
}},
31
{"VSetVarWomen": [
32
{
33
"v_id": "person4",
34
"attributes": {
35
"gender": "Female",
36
"id": "person4",
37
"@postedSet": [{
38
"from_type": "person",
39
"to_type": "post",
40
"directed": true,
41
"from_id": "person4",
42
"to_id": "3",
43
"attributes": {},
44
"e_type": "posted"
45
}]
46
},
47
"v_type": "person"
48
},
49
{
50
"v_id": "person5",
51
"attributes": {
52
"gender": "Female",
53
"id": "person5",
54
"@postedSet": [
55
{
56
"from_type": "person",
57
"to_type": "post",
58
"directed": true,
59
"from_id": "person5",
60
"to_id": "11",
61
"attributes": {},
62
"e_type": "posted"
63
},
64
{
65
"from_type": "person",
66
"to_type": "post",
67
"directed": true,
68
"from_id": "person5",
69
"to_id": "4",
70
"attributes": {},
71
"e_type": "posted"
72
}
73
]
74
},
75
"v_type": "person"
76
},
77
{
78
"v_id": "person2",
79
"attributes": {
80
"gender": "Female",
81
"id": "person2",
82
"@postedSet": [{
83
"from_type": "person",
84
"to_type": "post",
85
"directed": true,
86
"from_id": "person2",
87
"to_id": "1",
88
"attributes": {},
89
"e_type": "posted"
90
}]
91
},
92
"v_type": "person"
93
}
94
]},
95
{"VSetExpr": [
96
{
97
"v_id": "person4",
98
"attributes": {
100
"A.gender": "Female"
101
},
102
"v_type": "person"
103
},
104
{
105
"v_id": "person5",
106
"attributes": {
107
108
"A.gender": "Female"
109
},
110
"v_type": "person"
111
},
112
{
113
"v_id": "person2",
114
"attributes": {
115
116
"A.gender": "Female"
117
},
118
"v_type": "person"
119
}
120
]}
121
]
122
}
Copied!

Printing CSV to a FILE Object

Instead of printing output in JSON format, output can be written to a FILE object in comma-separated values (CSV) format. To select this option, at the end of the PRINT statement, include the keyword TO_CSV followed by the FILE object name:
PRINT to CSV FILE syntax example
1
PRINT @@setOfVertices TO_CSV file1;
Copied!
Each execution of the PRINT statement appends one line to the FILE. If the PRINT statement includes multiple expressions, then each printed value is separated from its neighbor by a comma. If an expression evaluates to a set or list, then the collection's values are delimited by single spaces. Due to the simpler format of CSV vs. JSON, the TO_CSV feature only supports data with a simple one- or two-dimension structure.
Limitations of PRINT > File
  • Printing a full Vertex set variable is not supported.
  • If a vertex is printed, only its ID value is printed.
  • If printing a vertex set's vertex-attached accumulator or a vertex set's variable, the result is a list of values, one for each vertex, separated by newlines.
  • The syntax for printing a vertex set expression is currently different when printing to a file than when printing to standard output. Compare:
    • PRINT A[A.gender]; # with brackets
    • PRINT A.gender TO_CSV file1; # without brackets
Writing to FILE objects is optimized for parallel processing. Consequently, the order in which data is written to the FILE is not guaranteed. Therefore, it is strongly recommended that the user design their queries such that one of these conditions is satisfied:
  1. 1.
    The query prints only one set of data, and the order of the set is not important.
  2. 2.
    Each line of data to print to a file includes a label which can be used to identify the data.
PRINT WHERE and PRINT TO_CSV FILE Object Example
1
CREATE QUERY printExampleFile() FOR GRAPH socialNet {
2
SetAccum<VERTEX> @@testSet, @@testSet2;
3
ListAccum<STRING> @@strList;
4
int x = 3;
5
FILE file1 ("/home/tigergraph/printExampleFile.txt");
6
7
Seed = person.*;
8
A = SELECT s
9
FROM Seed:s
10
WHERE s.gender == "Female"
11
ACCUM @@testSet += s, @@strList += s.gender;
12
A = SELECT s
13
FROM Seed:s
14
WHERE s.gender == "Male"
15
ACCUM @@testSet2 += s;
16
17
PRINT @@testSet, @@testSet2 TO_CSV file1; # 1st line: 2 4 5, 1 3 6 7 8 (order not guaranteed)
18
PRINT x WHERE x < 0 TO_CSV file1; # 2nd line: <skipped because no content>
19
PRINT x WHERE x > 0 TO_CSV file1; # 3rd line: 3
20
PRINT @@strList TO_CSV file1; # 4th line: Female Female Female
21
PRINT A.gender TO_CSV file1; # 5th line: Male\n Male\n Male\n Male\n Male
22
}
Copied!

FILE println statement

The FILE println statement writes data to a FILE object. Unlike the PRINT statement, which is a query-body level statement, the FILE println statement can be either a query-body level statement or a DML-sub-statement.
EBNF for FILE println statement
1
printlnStmt := fileVar".println" "(" expr ("," expr)* ")"
Copied!
println is a method of a FILE object variable. The println statement can be used either at the query-body level or a DML-sub-statement, e.g., within the ACCUM clause of a SELECT block. Each time println is called, it adds one new line of values to the FILE object, and then to the corresponding file.
The println function can print any expression that can be printed by a PRINT statement with the exception of vertex set variables. Vertex expression sets are also not applicable to the println function.
If the println statement has a list of expressions to print, it will produce a comma-separated list of values. If an expression refers to a list or set, then the output will be a list of values separated by spaces.
The data from query-body level FILE print statements (either TO_CSV or println) will appear in their original order. However, due to the parallel processing of statements in an ACCUM block, the order in which println statements at the DML-sub-statement level are processed cannot be guaranteed.

Example

File object query example
1
CREATE QUERY fileEx (STRING fileLocation) FOR GRAPH workNet {
2
3
FILE f1 (fileLocation);
4
P = {person.*};
5
6
PRINT "header" TO_CSV f1;
7
8
USWorkers = SELECT v FROM P:v
9
WHERE v.locationId == "us"
10
ACCUM f1.println(v.id, v.interestList);
11
12
PRINT "footer" TO_CSV f1;
13
}
14
INSTALL QUERY fileEx
15
RUN QUERY fileEx("/home/tigergraph/files")
Copied!
All of the PRINT statements in this example use the TO_CSV option, so there is no JSON output to the console.
Results from Query fileEx
1
GSQL > RUN QUERY fileEx("/home/tigergraph/fileEx.txt")
2
{
3
"error": false,
4
"message": "",
5
"version": {
6
"edition": "developer",
7
"schema": 0,
8
"api": "v2"
9
},
10
"results": []
11
}
Copied!
All the output in this case goes to the FILE object. In the query definition, the line "header" is printed first, followed by the println statements in the ACCUM clause, and "footer" is printed last. The output in the file follows this order because the order of query-body level statements is maintained in the output.
File contents produced by fileEx example
1
[tigergraph@localhost]$ more /home/tigergraph/fileEx.txt
2
header
3
person7,art sport
4
person10,football sport
5
person4,football
6
person9,financial teaching
7
person1,management financial
8
footer
Copied!
However, within the ACCUM clause itself, the order of the println statements is not guranteed.

Passing a FILE Object as a Parameter

A FILE Object can be passed from one query to a subquery. The subquery can then also write to the FILE object.
Example: query passing a FILE object to another query
1
CREATE QUERY fileParamSub(FILE f, STRING label, INT num) FOR GRAPH socialNet {
2
f.println(label, "header");
3
FOREACH i IN RANGE [1,2] DO
4
f.println(label, num+i);
5
END;
6
f.println(label, "footer");
7
}
8
9
CREATE QUERY fileParamMain(STRING mainlabel) FOR GRAPH socialNet {
10
FILE f ("/home/tigergraph/fileParam.txt");
11
f.println(mainlabel, "header");
12
FOREACH i IN RANGE [1,2] DO
13
f.println(mainlabel, i);
14
fileParamSub(f, " sub", 10*i);
15
END;
16
f.println(mainlabel, "footer");
17
}
Copied!
1
GSQL > RUN QUERY fileParamMain("main")
2
GSQL > EXIT
3
4
$ cat /home/tigergraph/fileParam.txt
5
main,header
6
main,1
7
sub,header
8
sub,11
9
sub,12
10
sub,footer
11
main,2
12
sub,header
13
sub,21
14
sub,22
15
sub,footer
16
main,footer
Copied!

LOG Statement

The LOG statement is another means to output data. It works as a function that outputs information to a log file.
EBNF for LOG statement
1
logStmt := LOG "(" condition "," argList ")"
Copied!
The first argument of the LOG statement is a boolean condition that enables or disables logging. This allows logging to be easily turned on/off, for uses such as debugging. After the condition, LOG takes one or more expressions (separated by commas). These expressions are evaluated and output to the log file.
Unlike the PRINT statement, which can only be used as a query-body statement, the LOG statement can be used as both a query-body statement and a DML-sub-statement.
The values will be recorded in the GPE log. To find the log file after the query has completed, open a Linux shell and use the command "gadmin log gpe". It may show you more than one log file name; use the one ending in "INFO". Search this file for "UDF_".
Examples
1
BOOLEAN debug = TRUE;
2
INT x = 10;
3
4
LOG(debug, 20);
5
LOG(debug, 10, x);
Copied!

RETURN Statement

EBNF for RETURN statement
1
returnStmt := RETURN expr
Copied!
The RETURN statement specifies data that a subquery passes back to an outer query that called the subquery. The return type for a RETURN statement can be any base type or accumulator type, but must be the same type as indicated by the RETURNS clause of the subquery.
For subqueries to return a HeapAccum or GroupByAccum, the accumulators must be defined at the catalog level. See the example below:
Subquery Returning HeapAccum Example
1
TYPEDEF tuple<name string, friends int> myTuple
2
TYPEDEF HeapAccum<myTuple>(3, friends DESC) myHeap
3
4
CREATE QUERY subquery1() FOR GRAPH socialNet RETURNS (myHeap){
5
myHeap @@heap; // Define the heap accumulator at the global level
6
SumAccum<int> @friends;
7
Start = {person.*};
8
Start = select s from Start:s-(friend:e)-:t
9
accum s.@friends += 1
10
post-accum @@heap += myTuple(s.id,s.@friends);
11
RETURN @@heap;
12
}
13
14
CREATE QUERY query1() FOR GRAPH socialNet {
15
PRINT subquery1();
16
}
Copied!