Run and Manage Queries

This page covers the query use phase of the query lifecycle: interpreting, running, and managing GSQL queries.

To define, compile, and install queries during the build phase, see Create and Install Queries.

This page also explains how to manage descriptions for queries and query parameters, including how to update, view, and remove them.

EBNF for query execution and management
interpretAnonymousQuery := INTERPRET QUERY
               [-QUEUE workload_query_name]
               "(" ")"
               [FOR GRAPH graphName]
               [SYNTAX syntaxName]
               "{" queryBody "}"

parameterValueList := parameterValue ["," parameterValue]*
parameterValue := parameterConstant
                | "[" parameterValue ["," parameterValue]* "]"  // BAG or SET
                | "(" stringLiteral "," stringLiteral ")"        // generic VERTEX value
parameterConstant := numeric | stringLiteral | TRUE | FALSE

runOrInterpretNamedQuery := (RUN | INTERPRET) QUERY [runOptions] queryName "(" parameterValueList | parameterValueJSON ")"
    ["-mode" ("legacy" | "instruction" | "debug")]

showQuery := SHOW QUERY queryName
dropQuery := DROP QUERY ( "*" | ALL | queryName ["," queryName]* )

For the createQuery and installQuery EBNF, see Create and Install Queries.

EBNF for DESCRIPTION OF QUERY
objectDescString := stringLiteral

updateDescription := UPDATE DESCRIPTION OF
	(QUERY queryName | QUERY_PARAM queryName"."paramName)
	[ON GRAPH graphName] objectDescString

showDescription := SHOW DESCRIPTION OF
	(QUERY ("*" | queryNamePrefix)
	| QUERY_PARAM queryName"."("*" | paramName)
	)
	[ON GRAPH graphName]

dropDescription := DROP DESCRIPTION OF
	(QUERY ("*" | queryName["," queryName]*)
	| QUERY_PARAM queryName"."("*" | paramName)["," queryName"."("*" | paramName)]*
	)
	[ON GRAPH graphName]

queryNamePrefix := name"*"

A query can be run in one of three ways:

  1. Define and run an unnamed query immediately:

    1. INTERPRET QUERY: execute the query’s statements

      Alternately, there is also a built-in REST++ endpoint to interpret a query string:
      POST /gsqlserver/interpreted_query
      See the RESTPP API User Guide for details.

  2. Define a named query and then run it.

    1. CREATE QUERY: define the functionality of the query

    2. INTERPRET QUERY: execute the query with input values

  3. Define a named query, compile it to optimize performance, and then run it.

    1. CREATE QUERY: define the functionality of the query

    2. INSTALL QUERY: compile the query

    3. RUN QUERY: execute the query with input values

There are some limitations to Interpreted Mode. See the section on Interpret a created query and the appendix section Interpreted GSQL Limitations.

INTERPRET QUERY

INTERPRET QUERY runs a query by translating it line-by-line. This is in contrast to the 2-step flow to install a query first and then run the query.

INTERPRET QUERY runs a query immediately but may take longer to finish than running an installed query. INTERPRET QUERY also has limitations and does not support all GSQL query language features.

There are two GSQL syntax options for Interpreted GSQL:

Interpret an anonymous query

Syntax for interpreting an anonymous query
interpretAnonymousQuery := INTERPRET QUERY
	       [-QUEUE workload_query_name]
	       "(" ")"
               [FOR GRAPH graph_name]
               [SYNTAX syntax_name]
               "{" queryBody "}"

Required privilege: No specific query privilege required.

This syntax is similar in concept to SQL queries. Queries are not named, do not accept parameters, and are not saved after being run.

Compare the example below to the CREATE QUERY example on Create and Install Queries:

  • No query name, no parameters, no RETURN statement.

  • Because no parameter is allowed, the parameter uid is set within the query.

Example of Immediate Mode for INTERPRET QUERY
INTERPRET QUERY () FOR GRAPH Social_Net {
    // declaration statements
    STRING uid = "Jane.Doe";
    users = {Person.*};
    // body statements
    posts = SELECT p
        FROM users:u-(Posted>)-:p
        WHERE u.id == uid;
    PRINT posts, posts.size();
}

Interpret a created query

Syntax for interpreting a created query
runOrInterpretNamedQuery := (RUN | INTERPRET) QUERY [runOptions] queryName "(" parameterValueList ")"
    ["-mode" ("legacy" | "instruction" | "debug")]

Required privilege: EXECUTE_QUERY

This syntax is similar to RUN QUERY, except:

  • The keyword RUN is replaced with INTERPRET.

  • The query runs immediately without installation.

  • The optional -mode flag lets you control how TigerGraph executes interpreted queries internally.

How interpreted queries run

When you use INTERPRET QUERY, TigerGraph executes the query using an interpreted engine.

Starting in 4.3, interpreted queries can run using one of two engines:

  • Instruction engine A newer engine designed to improve performance.

  • Standard interpret engine The original engine, which supports all GSQL features.

If you do not specify -mode, TigerGraph automatically selects the best engine. It prefers the instruction engine but switches to the standard engine if the query uses unsupported features.

You can explicitly choose the engine using the -mode option:

  • -mode instruction Use the instruction engine. The query fails if unsupported features are present.

  • -mode legacy Use the standard interpret engine. This engine supports all GSQL features.

  • -mode debug Use the instruction engine and generate debug files (serialized_instructions.json and serialized_instructions.bin) in /tmp/gpe under the TigerGraph installation directory. This option is intended for advanced troubleshooting.

Example of interpreting a query with different engines
INTERPRET QUERY myQuery("Jane.Doe")
INTERPRET QUERY myQuery("Jane.Doe") -mode instruction
INTERPRET QUERY myQuery("Jane.Doe") -mode legacy
INTERPRET QUERY myQuery("Jane.Doe") -mode debug

Checking which engine was used

You can confirm how TigerGraph executed the query by checking the GSQL logs.

  • Interpret query [query_name] in instruction mode

  • Interpret query [query_name] in old interpret engine

For more detail on why a query could not run in instruction mode, set the log level to DEBUG. Debug logs may include messages like:

Set instruction mode to false in function <name>

Errors related to engine selection

When you explicitly specify the -mode option, you may encounter one of the following errors:

  • Query [query_name] requires features supported only in instruction mode, but was run in legacy mode.

    You forced the standard engine, but the query requires instruction-only features.

  • Query [query_name] requires features supported only in legacy mode, but was run in instruction mode.

    You forced the instruction engine, but the query requires features supported only by the standard engine.

  • Query [query_name] contains features that require both instruction mode and legacy mode, and cannot be run in either mode.

    The query mixes features that are exclusive to both engines. Install the query and run it with RUN QUERY instead of INTERPRET QUERY.

RUN QUERY

The RUN QUERY command runs an installed query. To run a query with the RUN QUERY command, specify the query name, followed by the query parameters enclosed in parentheses. Running a query executes all statements in the query body and produces output as specified by the output statements in the query.

You can also run an installed query through REST requests - see Run an installed query.

Syntax

runOrInterpretNamedQuery := (RUN | INTERPRET) QUERY [runOptions] queryName
    "(" parameterValueList | parameterValueJSON ")"

runOptions := ( "-async"| "-av" | "-queue" <Workload Queue Name>)*
parameterValueList := parameterValue ["," parameterValue]*
parmeterValueJSON ::= '{"'parameterName'":' parameterValue(', "'parameterName'":' parameterValue)* '}'

Required privilege: EXECUTE_QUERY

To learn more about the -queue option, please refer Workload Management

Query parameters

There are two ways of passing parameters to a query in a RUN QUERY command:

These rules are for running a query in the GSQL CLI. Slightly different rules apply when running the query either with the RESTPP endpoint or with the newer GSQL endpoint.

Ordered list of Parameters

To pass parameters to a query with a list, the parameters must be put in the same order as they were in the query definition. Each value passed in will correspond to the parameter at the same index when the query was created.

To use the default value for a parameter, use the _ character for the value of the parameter. You can also omit parameters to use their default value. However, if you omit one parameter, you also have to omit all parameters that come after that parameter.

For example, if we have the following query definition:

CREATE QUERY greet_person(INT age = 3, STRING name = "John",
  DATETIME birthday = to_datetime("2019-02-19 19:19:19"))
{
  PRINT age, name, birthday;
}

To run the query with default values for the parameter name, use _ in the place of the second parameter value:

GSQL > RUN QUERY greet_person (21, _, "2020-02-02 20:02:20")
{
  "error": false,
  "message": "",
  "version": {
    "schema": 0,
    "edition": "enterprise",
    "api": "v2"
  },
  "results": [{
    "birthday": "2020-02-02 20:02:20",
    "name": "John",
    "age": 21
  }]
}

To use the default values for both the second and the third parameters, you can omit both parameters and only provide a value for the first parameter.

GSQL > RUN QUERY greet_person(21)
{
  "error": false,
  "message": "",
  "version": {
    "schema": 0,
    "edition": "enterprise",
    "api": "v2"
  },
  "results": [{
    "birthday": "2019-02-19 19:19:19",
    "name": "John",
    "age": 21
  }]
}

Parameters by name

Passing parameters as a JSON object has two advantages: they can be in any order, and you simply omit ones if you accept the default. To pass query parameters by name, map the parameter names to their values in a JSON object enclosed in parentheses. Parameters that are not named in the JSON object will keep their default values for the execution of the query.

For example, if we have the following query:

CREATE QUERY greet_person(INT age = 3, STRING name = "John",
  DATETIME birthday = to_datetime("2019-02-19 19:19:19"))
{
  PRINT age, name, birthday;
}

Supplying the parameters with a JSON object will look like the following. The parameter birthday is not named in the parameter JSON object and therefore takes the default value:

RUN QUERY greet_person( {"name": "Emma", "age": 21} )

Parameter format for complex types

This subsection describes how to format the complex type parameter values when executing a query by RUN QUERY.

More details about all parameter types are described in Query Parameter Types.

If a vertex type has a composite key, use a comma to separate the different attributes to denote their ID.

For example, if you have the following vertex definition:

CREATE VERTEX Composite_Person(id UINT, name STRING, age UINT, primary key (name, id))

A vertex ID would be "Tom,456", consisting of the name attribute and the id attribute.

Values in a parameter List

Parameter type Syntax Example

DATETIME

A string formatted as "YYYY-MM-DD HH-MM-SS"

"2019-02-19 19:19:19"

List/set/bag

Square brackets enclose a comma-separated list of values.

A collection of integers: [1,5,10]

Map

Divide the map in an ordered list of keys and a correspondingly ordered list of values: JSON object containing a "valuelist" object and a "keylist" object

An <INT, STRING> map:

{"keylist":[49,50], "valuelist":["Alaska","Hawaii"]}}

Typed vertex parameter: VERTEX<type>

If the vertex type is specified in the query definition, then the vertex argument is vertex_id

The vertex type is Person and the desired ID is person2. "person2"

Generic vertex parameter: VERTEX

If the type is not defined in the query definition, then the argument must be a tuple of strings with both the id and type: ("vertex_id", "vertex_type")

A vertex with ID person1 and type Person: ("person1","Person")

List/set/bag of generic VERTEX parameters

Square brackets enclose a comma-separated list of vertex (id, type) tuples. Mixed types are permitted.

[ ("person1","Person"),("11","Post") ]

Queries that could take any vertex type as input should be written using generic VERTEX parameters. Users who call these queries will provide ("id", "type") tuple arguments for these parameters.

Values in parameter by name

Each parameter has the form "<name>":<value>. The table below focuses on the <value> part.

Parameter type Syntax for Value Example

DATETIME

A string formatted as "YYYY-MM-DD HH-MM-SS"

"2023-01-01 00:00:00"

List/set/bag of primitives

A JSON array containing the primitive values

["a", "list", "of", "args"]

Map

Divide the map in an ordered list of keys and a correspondingly ordered list of values: JSON object containing a "valuelist" object and a "keylist" object

An <INT, STRING> map:

{"keylist":[49,50], "valuelist":["Alaska","Hawaii"]}}

VERTEX<type> (typed vertex parameter)

Since the type is already specified in the query, you only need to use a JSON object containing the field "id" for the vertex ID

{"id": "person1"}

VERTEX (generic vertex parameter)

Use a JSON object containing a field "id" for the vertex ID and a field "type" for the type of the vertex.

{"id": "person1","type": "Person"}

List/set/bag of VERTEX<type>

Use a JSON array containing a list of JSON VERTEX<type> objects

[{"id": "person1"}, {"id": "person2"}]

Options

All-vertex mode -av option

Some queries run with all or almost all vertices in a SELECT statement s, e.g. PageRank algorithm. In this case, the graph processing engine can run much more efficiently in all-vertex mode. In the all-vertex mode, all vertices are always selected, and the following actions become ineffective:

  • Filtering with selected vertices or vertex types. The source vertex set must be all vertices.

  • Filtering with the WHERE clause.

  • Filtering with the HAVING clause.

  • Assigning designated vertex or designated type of vertexes. E.g. X = { vertex_type .*}

To run the query in all-vertex mode, use the -av option in shell mode or include __GQUERY__USING_ALL_ACTIVE_MODE=true in the query string of an HTTP request.

GSQL > RUN QUERY -av test()

## In a curl URL call.  Note the use of both single and double underscores.
curl -X GET 'http://localhost:14240/restpp/query/graphname/queryname?__GQUERY__USING_ALL_ACTIVE_MODE=true'

Detached mode -async option

Typically, the GSQL RUN QUERY command runs in the foreground and does not produce output until the query completes, which is inconvenient in the case of long-running queries.

You can run queries in Detached Mode to enable background execution of long-running queries.

Queries executed in Detached mode are still subject to the system timeout limit. The default timeout limit is 16 seconds and can be set using the GSQL-TIMEOUT header.

To run a query in Detached Mode from the command line, use the-asyncoption for theRUN QUERYcommand:

GSQL > RUN QUERY -async <queryName>

You will receive a JSON response immediately containing a query ID (requestid):

{
  "error": false,
  "message": "The query is successfully submitted. Please check query status using the request id.",
  "requestid": "<RequestID>"
}

To run queries in Detached Mode via RESTPP endpoint call, use the GSQL-ASYNC header and set its value to true. If the query takes parameters, put them in the query string:

$ curl -s -H "GSQL-ASYNC:true" GET "http://localhost:14240/restpp/query/<graphName>/<queryName>?parameter1=<parameter1>

To check the status and results of the queries executed in Detached Mode, use the /query_status and the /query_result RESTPP endpoints.

Query Profiling -profile Option

The -PROFILE option allows you to activate query profiling when running a query in GSQL. Currently, the only supported value for profiling is BASIC, which enables basic query profiling to view and analyze execution details. By default, this option is empty, and profiling is not activated.

Example 1: Run query with profiling activated

RUN QUERY -PROFILE BASIC <queryName>

Example 2: Run query in async mode with profiling activated

RUN QUERY -ASYNC -PROFILE BASIC <queryName>

You can also use the -PROFILE option with the -async option to run the query asynchronously and retrieve real-time profiling data. This is useful for long-running queries where you need to monitor the execution while the query is still running. Once the query is submitted, you can use the /query_status API to get profiling data for that query.

Gzip compression

Use the -gzip option with RUN QUERY to request a gzip-compressed response. Use the -o option to specify the output file path.

RUN QUERY <queryName> -gzip -o "/path/to/zip.gz"
This option only works for installed queries. See Response size for details on when compression is applied.

GSQL Query output format

The standard output of GSQL queries is in industry-standard JSON format. A JSON object is an unordered set of key-value pairs, enclosed in curly braces. Among the acceptable data types for a JSON value are array and object. A JSON array is an ordered list of values, enclosed in square brackets. Since values can be objects or arrays, JSON supports hierarchical, nested structures. Strings are enclosed in double quotation marks. We also use the term field to refer to a key (or a key-value pair) of a given object.

At the top level of the JSON structure are four required fields ("version", "error", "message", and "results") and one dependent field ("code"). If a query is successful, the value of "error" will be "false", the "message" value will be empty, and the "results" value will be the intended output of the query. If an error or exception occurred during query execution, the "error" value will be "true", the "message" value will be a string message describing the error condition, and the "results" field will be empty. Also, the "code" field will contain an error code.

Beginning with version 2 (v2) of the output specification, an additional top-level field is required: "version". The "version" value is an object with the following fields:

Field Description

api

String specifying the output API version. Values are specified as follows:``v1'': Output API used in TigerGraph platform v0.8 through v1.0.

  • "v1" support is no longer available as of TigerGraph v3.0.

  • ”v2” (default): Output API introduced in TigerGraph platform v1.1 This is the latest API.

edition

String indicating the edition of the product.

schema

Integer representing which version of the user’s graph schema is currently in use. When a CREATE GRAPH statement is executed, the version is initialized to 0. Each time a SCHEMA_CHANGE JOB is run, the schema value is incremented by 1 (e.g., 1, 2, etc.)

Other top-level objects, such as "code" may appear in certain circumstances. Note that the top-level objects are enclosed in curly braces, meaning that they form an unordered set. They may appear in any order.

Below is an example of the output of a successful query:

Top Level JSON of a Valid Query - Example
{
  "version": {"edition": "developer","api": "v2","schema": "1"},
  "error": false,
  "message": "",
  "results": [
    {results_of_PRINT_statement_1},
    ...,
    {results_of_PRINT_statement_N}
  ]
}

The value of the "results" key-value pair is a sequential list of the data objects specified by the PRINT statements of the query. The list order follows the order of PRINT execution. The detailed format of the PRINT statement results is described in Output Statements and FILE Objects.

The following REST response misspells the name of the endpoint

GET echo/ Request and Response
curl -X GET "http://localhost:14240/restpp/eco"

and generates the following output:

{
  "version": {"edition":"developer","api":"v2","schema":0},
  "error": true,
  "message": "Endpoint is not found from url = /eco, please use GET /endpoints to list all valid endpoints.",
  "code": "REST-1000"
}

Changing the default output API

The following GSQL statement can be used to set the JSON output API configuration.

SET json_api = <version_string>
The only supported JSON API is "v2".

This statement sets a persistent system parameter. Each version of the TigerGraph platform is pre-configured to what was the latest output API that at the time of release.

SHOW QUERY

showQuery := SHOW QUERY queryName

Required privilege: READ_QUERY

To show the GSQL text of a query, run SHOW QUERY query_name . The query_name argument can use * or ? wildcards from Linux globbing, or it can be a regular expression when preceded by -r. See SHOW: View Parts of the Catalog

Additionally, the ls GSQL command lists all items on the graph and their statuses, including queries.

In this example, the output of the ls command has been truncated to show only the query statuses.

ls                       <--- show all queries

Queries:
  - draft1() (draft)
  - valid1() (installed v2)
  ...

SHOW QUERY *                <--- the flags are same as above

CREATE QUERY valid1(){          <-- no status is shown for a valid query that has not been installed
  PRINT 1;
}

# draft                          <-- a query that is set to DRAFT status because it calls a query with DRAFT status
CREATE QUERY draft_callDraft2(){
  draft2();
  PRINT "I am a draft too";
}

# installed v2                 <-- query is valid and has been installed successfully
CREATE QUERY valid2(){
  PRINT 1;
}

# deprecated                  <-- the query is deprecated if it is incompatible with the schema after a schema change
CREATE QUERY valid3(){
  v = SELECT src
      FROM unexistentType:src;
}

# blocked                    <-- the query is blocked by the file output policy
CREATE QUERY blockedQuery(){
  FILE f("/root");
}

# disabled                   <-- the query is disabled if it calls a deleted sub-query.
CREATE QUERY disabledQuery(){
  deletedQuery();
}

# pendingInstall            <-- the query is installing
CREATE QUERY valid3(){
  PRINT 1;
}

# failedCompilation         <-- query installation failed
CREATE QUERY valid3(){
  PRINT 1;
}

DROP QUERY

dropQuery := DROP QUERY ( "*" | ALL | queryName ["," queryName]* )

Required privilege: DROP_QUERY

To drop a query, run DROP QUERY query_name. The query will be uninstalled (if it has been installed) and removed from the dictionary. If a subquery is dropped, the main query is marked as disabled.

In this example, using a graph g, a test query A is created, followed by a test query B that calls A(). After A is dropped, B is disabled.

GSQL > create query A(){print 1;}
Successfully created queries: [A].

GSQL > create query B(){ A();}
Successfully created queries: [B].

GSQL > install query *
Start installing queries, about 1 minute ...
<....>
Query installation finished.

GSQL > drop query A
Successfully dropped queries on the graph 'g': [A].

GSQL > ls
---- Graph g
Vertex Types:
Edge Types:

Graphs:
  - Graph g()
Jobs:
Queries:
  - B() (disabled)

Both valid and draft queries can be dropped.

To drop all queries, either of the following commands can be used:

  • DROP QUERY ALL

  • DROP QUERY *

The scope of the command depends on the user’s current scope. If the user has set a working graph, then DROP ALL removes all the queries for that graph. If a user has set their scope to be global, then DROP ALL removes all queries across all graph spaces.

Query Descriptions

A query description provides a human-readable explanation of a query or its parameters, offering more detailed information to help users understand the query’s purpose and functionality. Here, you will find how to update, show, and drop descriptions of queries and query parameters.

Update description

After creating a query, you can add a description for the query.

Syntax

UPDATE DESCRIPTION OF <objectType> <objectName> [ON GRAPH <graphName>] <description>

Required privilege WRITE_QUERY

To update a description, run the UPDATE DESCRIPTION command as shown below. You can update the description of a query or a query parameter. If you choose not to specify a graph in the command, the current scope will be used as the scope of the description.

GSQL > USE GRAPH poc_graph
GSQL > UPDATE DESCRIPTION OF QUERY query1 "List of all employees in the company"
GSQL > UPDATE DESCRIPTION OF QUERY query2 ON GRAPH graph1 "Details of employees in a specific department"
GSQL > UPDATE DESCRIPTION OF QUERY_PARAM query1.param1 "Department where the employee works"

The term UPDATE here means adding a description to the target. If the target does not already have a description, it will be added. If the target already has a description, it will be replaced with the new one.

  • When updating a query, use CREATE OR REPLACE QUERY instead of CREATE QUERY to retain the query description.

  • CREATE QUERY may unintentionally drop both the query and its description if it already exists, whereas CREATE OR REPLACE QUERY ensures the description is retained by replacing the query without dropping it.

Show description

The SHOW DESCRIPTION command displays the descriptions of the queries or query parameters that match the given objectName.

Syntax

SHOW DESCRIPTION OF <objectType> <objectName> [ON GRAPH <graphName>]

Required privilege READ_QUERY

To display a description, use the SHOW DESCRIPTION command as shown below. Similar to the update command, you can display the description of a query or a query parameter.

GSQL > USE GRAPH poc_graph
GSQL > SHOW DESCRIPTION OF QUERY query1
GSQL > SHOW DESCRIPTION OF QUERY query1*
GSQL > SHOW DESCRIPTION OF QUERY * ON GRAPH poc_graph
GSQL > SHOW DESCRIPTION OF QUERY_PARAM query1.param1
GSQL > SHOW DESCRIPTION OF QUERY_PARAM query2.*
  • The wildcard * can be used to match multiple queries or parameters.

    • * by itself means all queries in this graph.

    • prefix* means all queries whose name starts with prefix.

    • queryName.* means all parameters of queryName.

Drop description

The DROP DESCRIPTION removes descriptions of queries or query parameters.

Syntax

DROP DESCRIPTION OF <objectType> <objectName(s)> [ON GRAPH <graphName>]
  • <objectName(s)> can include a comma-separated list of names.

  • For the DROP DESCRIPTION command, you can specify multiple queries or parameters in a single command using a comma-separated list.

Required privilege WRITE_QUERY

To remove a description, run the DROP DESCRIPTION command as shown below.

GSQL > USE GRAPH poc_graph
GSQL > DROP DESCRIPTION OF QUERY query1
GSQL > DROP DESCRIPTION OF QUERY * ON GRAPH poc_graph
GSQL > DROP DESCRIPTION OF QUERY_PARAM query1.param1
GSQL > DROP DESCRIPTION OF QUERY_PARAM query1.param1,query1.param2
GSQL > DROP DESCRIPTION OF QUERY_PARAM query1.*

Support is provided for dropping descriptions of multiple targets simultaneously. You can use the wildcard * to remove descriptions of all queries or all parameters of a specific query. The query parameter’s description is independent of the query’s description. Therefore, after dropping the query description, the query parameter’s description remains unaffected.

  • Wildcards: SHOW supports * to both queries and parameters, while DROP only supports * to remove descriptions of all queries or parameters.

  • List of Objects: SHOW cannot specify multiple objects in a comma-separated list, whereas DROP can.