跳到主要内容
版本:3.10.0

nGQL cheatsheet

Functions

  • Math functions

    FunctionDescription
    double abs(double x)Returns the absolute value of the argument.
    double floor(double x)Returns the largest integer value smaller than or equal to the argument. (Rounds down)
    double ceil(double x)Returns the smallest integer greater than or equal to the argument. (Rounds up)
    double round(double x)Returns the integer value nearest to the argument. Returns a number farther away from 0 if the argument is in the middle.
    double sqrt(double x)Returns the square root of the argument.
    double cbrt(double x)Returns the cubic root of the argument.
    double hypot(double x, double y)Returns the hypotenuse of a right-angled triangle.
    double pow(double x, double y)Returns the result of x^y^.
    double exp(double x)Returns the result of e^x^.
    double exp2(double x)Returns the result of 2^x^.
    double log(double x)Returns the base-e logarithm of the argument.
    double log2(double x)Returns the base-2 logarithm of the argument.
    double log10(double x)Returns the base-10 logarithm of the argument.
    double sin(double x)Returns the sine of the argument.
    double asin(double x)Returns the inverse sine of the argument.
    double cos(double x)Returns the cosine of the argument.
    double acos(double x)Returns the inverse cosine of the argument.
    double tan(double x)Returns the tangent of the argument.
    double atan(double x)Returns the inverse tangent of the argument.
    double rand()Returns a random floating point number in the range from 0 (inclusive) to 1 (exclusive); i.e.[0,1).
    int rand32(int min, int max)Returns a random 32-bit integer in [min, max).
    If you set only one argument, it is parsed as max and min is 0 by default.
    If you set no argument, the system returns a random signed 32-bit integer.
    int rand64(int min, int max)Returns a random 64-bit integer in [min, max).
    If you set only one argument, it is parsed as max and min is 0 by default.
    If you set no argument, the system returns a random signed 64-bit integer.
    bit_and()Bitwise AND.
    bit_or()Bitwise OR.
    bit_xor()Bitwise XOR.
    int size()Returns the number of elements in a list or a map or the length of a string.
    int range(int start, int end, int step)Returns a list of integers from [start,end] in the specified steps. step is 1 by default.
    int sign(double x)Returns the signum of the given number.
    If the number is 0, the system returns 0.
    If the number is negative, the system returns -1.
    If the number is positive, the system returns 1.
    double e()Returns the base of the natural logarithm, e (2.718281828459045).
    double pi()Returns the mathematical constant pi (3.141592653589793).
    double radians()Converts degrees to radians. radians(180) returns 3.141592653589793.
  • Aggregating functions

    FunctionDescription
    avg()Returns the average value of the argument.
    count()Syntax: count({expr | *}).
    count()returns the number of rows (including NULL).
    count(expr)returns the number of non-NULL values that meet the expression.
    count() and size() are different.
    max()Returns the maximum value.
    min()Returns the minimum value.
    collect()The collect() function returns a list containing the values returned by an expression. Using this function aggregates data by merging multiple records or values into a single list.
    std()Returns the population standard deviation.
    sum()Returns the sum value.
  • String functions

    FunctionDescription
    int strcasecmp(string a, string b)Compares string a and b without case sensitivity. When a = b, the return
    string lower(string a)Returns the argument in lowercase.
    string toLower(string a)The same as lower().
    string upper(string a)Returns the argument in uppercase.
    string toUpper(string a)The same as upper().
    int length(a)Returns the length of the given string in bytes or the length of a path in hops.
    string trim(string a)Removes leading and trailing spaces.
    string ltrim(string a)Removes leading spaces.
    string rtrim(string a)Removes trailing spaces.
    string left(string a, int count)Returns a substring consisting of count characters from the left side of
    string right(string a, int count)Returns a substring consisting of count characters from the right side of
    string lpad(string a, int size, string letters)Left-pads string a with string letters and returns a
    string rpad(string a, int size, string letters)Right-pads string a with string letters and returns a
    string substr(string a, int pos, int count)Returns a substring extracting count characters starting from
    string substring(string a, int pos, int count)The same as substr().
    string reverse(string)Returns a string in reverse order.
    string replace(string a, string b, string c)Replaces string b in string a with string c.
    list split(string a, string b)Splits string a at string b and returns a list of strings.
    concat()The concat() function requires at least two or more strings. All the parameters are concatenated into one string.
    Syntax: concat(string1,string2,...)
    concat_ws()The concat_ws() function connects two or more strings with a predefined separator.
    extract()extract() uses regular expression matching to retrieve a single substring or all substrings from a string.
    json_extract()The json_extract() function converts the specified JSON string to map.
  • Data and time functions

    FunctionDescription
    int now()Returns the current timestamp of the system.
    timestamp timestamp()Returns the current timestamp of the system.
    date date()Returns the current UTC date based on the current system.
    time time()Returns the current UTC time based on the current system.
    datetime datetime()Returns the current UTC date and time based on the current system.
  • Schema-related functions

    • For nGQL statements

      FunctionDescription
      id(vertex)Returns the ID of a vertex. The data type of the result is the same as the vertex ID.
      map properties(vertex)Returns the properties of a vertex.
      map properties(edge)Returns the properties of an edge.
      string type(edge)Returns the edge type of an edge.
      src(edge)Returns the source vertex ID of an edge. The data type of the result is the same as the vertex ID.
      dst(edge)Returns the destination vertex ID of an edge. The data type of the result is the same as the vertex ID.
      int rank(edge)Returns the rank value of an edge.
      vertexReturns the information of vertices, including VIDs, tags, properties, and values.
      edgeReturns the information of edges, including edge types, source vertices, destination vertices, ranks, properties, and values.
      verticesReturns the information of vertices in a subgraph. For more information, see GET SUBGRAPH.
      edgesReturns the information of edges in a subgraph. For more information, see GET SUBGRAPH.
      pathReturns the information of a path. For more information, see FIND PATH.
    • For statements compatible with openCypher

      FunctionDescription
      id(<vertex\>)Returns the ID of a vertex. The data type of the result is the same as the vertex ID.
      list tags(<vertex\>)Returns the Tag of a vertex, which serves the same purpose as labels().
      list labels(<vertex\>)Returns the Tag of a vertex, which serves the same purpose as tags(). This function is used for compatibility with openCypher syntax.
      map properties(<vertex_or_edge\>)Returns the properties of a vertex or an edge.
      string type(<edge\>)Returns the edge type of an edge.
      src(<edge\>)Returns the source vertex ID of an edge. The data type of the result is the same as the vertex ID.
      dst(<edge\>)Returns the destination vertex ID of an edge. The data type of the result is the same as the vertex ID.
      vertex startNode(<path\>)Visits an edge or a path and returns its source vertex ID.
      string endNode(<path\>)Visits an edge or a path and returns its destination vertex ID.
      int rank(<edge\>)Returns the rank value of an edge.
  • List functions

    FunctionDescription
    keys(expr)Returns a list containing the string representations for all the property names of vertices, edges, or maps.
    labels(vertex)Returns the list containing all the tags of a vertex.
    nodes(path)Returns the list containing all the vertices in a path.
    range(start, end [, step])Returns the list containing all the fixed-length steps in [start,end]. step is 1 by default.
    relationships(path)Returns the list containing all the relationships in a path.
    reverse(list)Returns the list reversing the order of all elements in the original list.
    tail(list)Returns all the elements of the original list, excluding the first one.
    head(list)Returns the first element of a list.
    last(list)Returns the last element of a list.
    reduce()The reduce() function applies an expression to each element in a list one by one, chains the result to the next iteration by taking it as the initial value, and returns the final result.
  • Type conversion functions

    FunctionDescription
    bool toBoolean()Converts a string value to a boolean value.
    float toFloat()Converts an integer or string value to a floating point number.
    string toString()Converts non-compound types of data, such as numbers, booleans, and so on, to strings.
    int toInteger()Converts a floating point or string value to an integer value.
    set toSet()Converts a list or set value to a set value.
    int hash()The hash() function returns the hash value of the argument. The argument can be a number, a string, a list, a boolean, null, or an expression that evaluates to a value of the preceding data types.
  • Predicate functions

    Predicate functions return true or false. They are most commonly used in WHERE clauses.

    <predicate>(<variable> IN <list> WHERE <condition>)
    FunctionDescription
    exists()Returns true if the specified property exists in the vertex, edge or map. Otherwise, returns false.
    any()Returns true if the specified predicate holds for at least one element in the given list. Otherwise, returns false.
    all()Returns true if the specified predicate holds for all elements in the given list. Otherwise, returns false.
    none()Returns true if the specified predicate holds for no element in the given list. Otherwise, returns false.
    single()Returns true if the specified predicate holds for exactly one of the elements in the given list. Otherwise, returns false.
  • Conditional expressions functions

    FunctionDescription
    CASEThe CASE expression uses conditions to filter the result of an nGQL query statement. It is usually used in the YIELD and RETURN clauses. The CASE expression will traverse all the conditions. When the first condition is met, the CASE expression stops reading the conditions and returns the result. If no conditions are met, it returns the result in the ELSE clause. If there is no ELSE clause and no conditions are met, it returns NULL.
    coalesce()Returns the first not null value in all expressions.

General queries statements

  • MATCH

    MATCH <pattern> [<clause_1>] RETURN <output> [<clause_2>];
    PatternExampleDescription
    Match vertices(v)You can use a user-defined variable in a pair of parentheses to represent a vertex in a pattern. For example: (v).
    Match tagsMATCH (v:player) RETURN vYou can specify a tag with :<tag_name> after the vertex in a pattern.
    Match multiple tagsMATCH (v:player:team) RETURN vTo match vertices with multiple tags, use colons (:).
    Match vertex propertiesMATCH (v:player{name:"Tim Duncan"}) RETURN v

    MATCH (v) WITH v, properties(v) as props, keys(properties(v)) as kk WHERE [i in kk where props[i] == "Tim Duncan"] RETURN v
    You can specify a vertex property with {<prop_name>: <prop_value>} after the tag in a pattern; or use a vertex property value to get vertices directly.
    Match a VID.MATCH (v) WHERE id(v) == 'player101' RETURN vYou can use the VID to match a vertex. The id() function can retrieve the VID of a vertex.
    Match multiple VIDs.MATCH (v:player { name: 'Tim Duncan' })--(v2) WHERE id(v2) IN ["player101", "player102"] RETURN v2To match multiple VIDs, use WHERE id(v) IN [vid_list].
    Match connected verticesMATCH (v:player{name:"Tim Duncan"})--(v2) RETURN v2.player.name AS NameYou can use the -- symbol to represent edges of both directions and match vertices connected by these edges. You can add a > or < to the -- symbol to specify the direction of an edge.
    Match pathsMATCH p=(v:player{name:"Tim Duncan"})-->(v2) RETURN pConnected vertices and edges form a path. You can use a user-defined variable to name a path as follows.
    Match edgesMATCH (v:player{name:"Tim Duncan"})-[e]-(v2) RETURN e
    MATCH ()<-[e]-() RETURN e
    Besides using --, -->, or <-- to indicate a nameless edge, you can use a user-defined variable in a pair of square brackets to represent a named edge. For example: -[e]-.
    Match an edge typeMATCH ()-[e:follow]-() RETURN eJust like vertices, you can specify an edge type with :<edge_type> in a pattern. For example: -[e:follow]-.
    Match edge type properties MATCH (v:player{name:"Tim Duncan"})-[e:follow{degree:95}]->(v2) RETURN e

    MATCH ()-[e]->() WITH e, properties(e) as props, keys(properties(e)) as kk WHERE [i in kk where props[i] == 90] RETURN e
    You can specify edge type properties with {<prop_name>: <prop_value>} in a pattern. For example: [e:follow{likeness:95}]; or use an edge type property value to get edges directly.
    Match multiple edge typesMATCH (v:player{name:"Tim Duncan"})-[e:follow | :serve]->(v2) RETURN eThe | symbol can help matching multiple edge types. For example: [e:follow |:serve]. The English colon (:) before the first edge type cannot be omitted, but the English colon before the subsequent edge type can be omitted, such as [e:follow |serve].
    Match multiple edgesMATCH (v:player{name:"Tim Duncan"})-[]->(v2)<-[e:serve]-(v3) RETURN v2, v3You can extend a pattern to match multiple edges in a path.
    Match fixed-length pathsMATCH p=(v:player{name:"Tim Duncan"})-[e:follow*2]->(v2) RETURN DISTINCT v2 AS FriendsYou can use the :<edge_type>*<hop> pattern to match a fixed-length path. hop must be a non-negative integer. The data type of e is the list.
    Match variable-length pathsMATCH p=(v:player{name:"Tim Duncan"})-[e:follow*1..3]->(v2) RETURN v2 AS FriendsminHop: Optional. It represents the minimum length of the path. minHop: must be a non-negative integer. The default value is 1.
    minHop and maxHop are optional and the default value is 1 and infinity respectively. The data type of e is the list.
    Match variable-length paths with multiple edge typesMATCH p=(v:player{name:"Tim Duncan"})-[e:follow | serve*2]->(v2) RETURN DISTINCT v2You can specify multiple edge types in a fixed-length or variable-length pattern. In this case, hop, minHop, and maxHop take effect on all edge types. The data type of e is the list.
    Retrieve vertex or edge informationMATCH (v:player{name:"Tim Duncan"}) RETURN v
    MATCH (v:player{name:"Tim Duncan"})-[e]->(v2) RETURN e
    Use RETURN {<vertex_name> | <edge_name>} to retrieve all the information of a vertex or an edge.
    Retrieve VIDsMATCH (v:player{name:"Tim Duncan"}) RETURN id(v)Use the id() function to retrieve VIDs.
    Retrieve tagsMATCH (v:player{name:"Tim Duncan"}) RETURN labels(v)Use the labels() function to retrieve the list of tags on a vertex.
    To retrieve the nth element in the labels(v) list, use labels(v)[n-1].
    Retrieve a single property on a vertex or an edgeMATCH (v:player{name:"Tim Duncan"}) RETURN v.player.ageUse RETURN {<vertex_name> | <edge_name>}.<property> to retrieve a single property.
    Use AS to specify an alias for a property.
    Retrieve all properties on a vertex or an edgeMATCH p=(v:player{name:"Tim Duncan"})-[]->(v2) RETURN properties(v2)Use the properties() function to retrieve all properties on a vertex or an edge.
    Retrieve edge typesMATCH p=(v:player{name:"Tim Duncan"})-[e]->() RETURN DISTINCT type(e)Use the type() function to retrieve the matched edge types.
    Retrieve pathsMATCH p=(v:player{name:"Tim Duncan"})-[*3]->() RETURN pUse RETURN <path_name> to retrieve all the information of the matched paths.
    Retrieve vertices in a pathMATCH p=(v:player{name:"Tim Duncan"})-[]->(v2) RETURN nodes(p)Use the nodes() function to retrieve all vertices in a path.
    Retrieve edges in a pathMATCH p=(v:player{name:"Tim Duncan"})-[]->(v2) RETURN relationships(p)Use the relationships() function to retrieve all edges in a path.
    Retrieve path lengthMATCH p=(v:player{name:"Tim Duncan"})-[*..2]->(v2) RETURN p AS Paths, length(p) AS LengthUse the length() function to retrieve the length of a path.
  • OPTIONAL MATCH

    PatternExampleDescription
    Matches patterns against your graph database, just like MATCH does.MATCH (m)-[]->(n) WHERE id(m)=="player100" OPTIONAL MATCH (n)-[]->(l) RETURN id(m),id(n),id(l)If no matches are found, OPTIONAL MATCH will use a null for missing parts of the pattern.
  • LOOKUP

    LOOKUP ON {<vertex_tag> | <edge_type>}
    [WHERE <expression> [AND <expression> ...]]
    YIELD <return_list> [AS <alias>]
    PatternExampleDescription
    Retrieve verticesLOOKUP ON player WHERE player.name == "Tony Parker" YIELD player.name AS name, player.age AS ageThe following example returns vertices whose name is Tony Parker and the tag is player.
    Retrieve edgesLOOKUP ON follow WHERE follow.degree == 90 YIELD follow.degreeReturns edges whose degree is 90 and the edge type is follow.
    List vertices with a tagLOOKUP ON player YIELD properties(vertex),id(vertex)Shows how to retrieve the VID of all vertices tagged with player.
    List edges with an edge typesLOOKUP ON follow YIELD edge AS eShows how to retrieve the source Vertex IDs, destination vertex IDs, and ranks of all edges of the follow edge type.
    Count the numbers of vertices or edges`LOOKUP ON player YIELD id(vertex)YIELD COUNT(*) AS Player_Count`
    Count the numbers of edges`LOOKUP ON follow YIELD edge as eYIELD COUNT(*) AS Like_Count`
  • GO

    GO [[<M> TO] <N> {STEP|STEPS} ] FROM <vertex_list>
    OVER <edge_type_list> [{REVERSELY | BIDIRECT}]
    [ WHERE <conditions> ]
    YIELD [DISTINCT] <return_list>
    [{SAMPLE <sample_list> | LIMIT <limit_list>}]
    [| GROUP BY {col_name | expr | position} YIELD <col_name>]
    [| ORDER BY <expression> [{ASC | DESC}]]
    [| LIMIT [<offset_value>,] <number_rows>]
    ExampleDescription
    GO FROM "player102" OVER serve YIELD dst(edge)Returns the teams that player 102 serves.
    GO 2 STEPS FROM "player102" OVER follow YIELD dst(edge)Returns the friends of player 102 with 2 hops.
    GO FROM "player100", "player102" OVER serve WHERE properties(edge).start_year > 1995 YIELD DISTINCT properties($$).name AS team_name, properties(edge).start_year AS start_year, properties($^).name AS player_nameAdds a filter for the traversal.
    GO FROM "player100" OVER follow, serve YIELD properties(edge).degree, properties(edge).start_yearThe following example traverses along with multiple edge types. If there is no value for a property, the output is NULL.
    GO FROM "player100" OVER follow REVERSELY YIELD src(edge) AS destinationThe following example returns the neighbor vertices in the incoming direction of player 100.
    `GO FROM "player100" OVER follow REVERSELY YIELD src(edge) AS idGO FROM .idOVERserveWHEREproperties(-.id OVER serve WHERE properties(^).age > 20 YIELD properties($^).name AS FriendOf, properties($$).name AS Team`
    GO FROM "player102" OVER follow YIELD dst(edge) AS bothThe following example returns all the neighbor vertices of player 102.
    `GO 2 STEPS FROM "player100" OVER follow YIELD src(edge) AS src, dst(edge) AS dst, properties($$).age AS ageGROUP BY .dstYIELD-.dst YIELD -.dst AS dst, collect_set(.src)ASsrc,collect(-.src) AS src, collect(-.age) AS age`
  • FETCH

    • Fetch vertex properties

      FETCH PROP ON {<tag_name>[, tag_name ...] | *}
      <vid> [, vid ...]
      YIELD <return_list> [AS <alias>]
      ExampleDescription
      FETCH PROP ON player "player100" YIELD properties(vertex)Specify a tag in the FETCH statement to fetch the vertex properties by that tag.
      FETCH PROP ON player "player100" YIELD player.name AS nameUse a YIELD clause to specify the properties to be returned.
      FETCH PROP ON player "player101", "player102", "player103" YIELD properties(vertex)Specify multiple VIDs (vertex IDs) to fetch properties of multiple vertices. Separate the VIDs with commas.
      FETCH PROP ON player, t1 "player100", "player103" YIELD properties(vertex)Specify multiple tags in the FETCH statement to fetch the vertex properties by the tags. Separate the tags with commas.
      FETCH PROP ON * "player100", "player106", "team200" YIELD properties(vertex)Set an asterisk symbol * to fetch properties by all tags in the current graph space.
    • Fetch edge properties

      FETCH PROP ON <edge_type> <src_vid> -> <dst_vid>[@<rank>] [, <src_vid> -> <dst_vid> ...]
      YIELD <output>;
      ExampleDescription
      FETCH PROP ON serve "player100" -> "team204" YIELD properties(edge)The following statement fetches all the properties of the serve edge that connects vertex "player100" and vertex "team204".
      FETCH PROP ON serve "player100" -> "team204" YIELD serve.start_yearUse a YIELD clause to fetch specific properties of an edge.
      FETCH PROP ON serve "player100" -> "team204", "player133" -> "team202" YIELD properties(edge)Specify multiple edge patterns (<src_vid> -> <dst_vid>[@<rank>]) to fetch properties of multiple edges. Separate the edge patterns with commas.
      FETCH PROP ON serve "player100" -> "team204"@1 YIELD properties(edge)To fetch on an edge whose rank is not 0, set its rank in the FETCH statement.
      `GO FROM "player101" OVER follow YIELD follow._src AS s, follow._dst AS dFETCH PROP ON follow .s>-.s -> -.d YIELD follow.degree`
      $var = GO FROM "player101" OVER follow YIELD follow._src AS s, follow._dst AS d; FETCH PROP ON follow $var.s -> $var.d YIELD follow.degreeYou can use user-defined variables to construct similar queries.
  • SHOW

    StatementSyntaxExampleDescription
    SHOW CHARSETSHOW CHARSETSHOW CHARSETShows the available character sets.
    SHOW COLLATIONSHOW COLLATIONSHOW COLLATIONShows the collations supported by NebulaGraph.
    SHOW CREATE SPACESHOW CREATE SPACE <space_name>SHOW CREATE SPACE basketballplayerShows the creating statement of the specified graph space.
    SHOW CREATE TAG/EDGESHOW CREATE {TAG <tag_name> | EDGE <edge_name>}SHOW CREATE TAG playerShows the basic information of the specified tag.
    SHOW HOSTSSHOW HOSTS [GRAPH | STORAGE | META]SHOW HOSTS
    SHOW HOSTS GRAPH
    Shows the host and version information of Graph Service, Storage Service, and Meta Service.
    SHOW INDEX STATUSSHOW {TAG | EDGE} INDEX STATUSSHOW TAG INDEX STATUSShows the status of jobs that rebuild native indexes, which helps check whether a native index is successfully rebuilt or not.
    SHOW INDEXESSHOW {TAG | EDGE} INDEXESSHOW TAG INDEXESShows the names of existing native indexes.
    SHOW PARTSSHOW PARTS [<part_id>]SHOW PARTSShows the information of a specified partition or all partitions in a graph space.
    SHOW ROLESSHOW ROLES IN <space_name>SHOW ROLES in basketballplayerShows the roles that are assigned to a user account.
    SHOW SNAPSHOTSSHOW SNAPSHOTSSHOW SNAPSHOTSShows the information of all the snapshots.
    SHOW SPACESSHOW SPACESSHOW SPACESShows existing graph spaces in NebulaGraph.
    SHOW STATSSHOW STATSSHOW STATSShows the statistics of the graph space collected by the latest STATS job.
    SHOW TAGS/EDGES`SHOW TAGSEDGES`SHOW TAGS,SHOW EDGES
    SHOW USERSSHOW USERSSHOW USERSShows the user information.
    SHOW SESSIONSSHOW SESSIONS SHOW SESSIONSShows the information of all the sessions.
    SHOW SESSIONSSHOW SESSION <Session_Id>SHOW SESSION 1623304491050858Shows a specified session with its ID.
    SHOW QUERIESSHOW [ALL] QUERIESSHOW QUERIESShows the information of working queries in the current session.
    SHOW META LEADERSHOW META LEADERSHOW META LEADERShows the information of the leader in the current Meta cluster.

Clauses and options

ClauseSyntaxExampleDescription
GROUP BY GROUP BY <var> YIELD <var>, <aggregation_function(var)>`GO FROM "player100" OVER follow BIDIRECT YIELD $$.player.name as NameGROUP BY .NameYIELD-.Name YIELD -.Name as Player, count(*) AS Name_Count`
LIMITYIELD <var> [| LIMIT [<offset_value>,] <number_rows>]`GO FROM "player100" OVER follow REVERSELY YIELD .player.nameASFriend,.player.name AS Friend, .player.age AS AgeORDER BY .Age,-.Age, -.Friend
SKIPRETURN <var> [SKIP <offset>] [LIMIT <number_rows>]MATCH (v:player{name:"Tim Duncan"}) --> (v2) RETURN v2.player.name AS Name, v2.player.age AS Age ORDER BY Age DESC SKIP 1SKIP can be used alone to set the offset and return the data after the specified position.
SAMPLE<go_statement> SAMPLE <sample_list>;GO 3 STEPS FROM "player100" OVER * YIELD properties($$).name AS NAME, properties($$).age AS Age SAMPLE [1,2,3];Takes samples evenly in the result set and returns the specified amount of data.
ORDER BY<YIELD clause> ORDER BY <expression> [ASC | DESC] [, <expression> [ASC | DESC] ...]`FETCH PROP ON player "player100", "player101", "player102", "player103" YIELD player.age AS age, player.name AS nameORDER BY .ageASC,-.age ASC, -.name DESC`
RETURNRETURN {<vertex_name>|<edge_name>|<vertex_name>.<property>|<edge_name>.<property>|...}MATCH (v:player) RETURN v.player.name, v.player.age LIMIT 3Returns the first three rows with values of the vertex properties name and age.
TTLCREATE TAG <tag_name>(<property_name_1> <property_value_1>, <property_name_2> <property_value_2>, ...) ttl_duration= <value_int>, ttl_col = <property_name>CREATE TAG t2(a int, b int, c string) ttl_duration= 100, ttl_col = "a"Create a tag and set the TTL options.
WHEREWHERE {<vertex|edge_alias>.<property_name> {>|==|<|...} <value>...}MATCH (v:player) WHERE v.player.name == "Tim Duncan" XOR (v.player.age < 30 AND v.player.name == "Yao Ming") OR NOT (v.player.name == "Yao Ming" OR v.player.name == "Tim Duncan") RETURN v.player.name, v.player.ageThe WHERE clause filters the output by conditions. The WHERE clause usually works in Native nGQL GO and LOOKUP statements, and OpenCypher MATCH and WITH statements.
YIELDYIELD [DISTINCT] <col> [AS <alias>] [, <col> [AS <alias>] ...] [WHERE <conditions>];`GO FROM "player100" OVER follow YIELD dst(edge) AS IDFETCH PROP ON player $-.ID YIELD player.age AS Age
WITHMATCH $expressions WITH {nodes()|labels()|...}MATCH p=(v:player{name:"Tim Duncan"})--() WITH nodes(p) AS n UNWIND n AS n1 RETURN DISTINCT n1The WITH clause can retrieve the output from a query part, process it, and pass it to the next query part as the input.
UNWINDUNWIND <list> AS <alias> <RETURN clause>UNWIND [1,2,3] AS n RETURN nSplits a list into rows.

Space statements

StatementSyntaxExampleDescription
CREATE SPACECREATE SPACE [IF NOT EXISTS] <graph_space_name> ( [partition_num = <partition_number>,] [replica_factor = <replica_number>,] vid_type = {FIXED_STRING(<N>) | INT[64]} ) [COMMENT = '<comment>']CREATE SPACE my_space_1 (vid_type=FIXED_STRING(30))Creates a graph space with
CREATE SPACECREATE SPACE <new_graph_space_name> AS <old_graph_space_name>CREATE SPACE my_space_4 as my_space_3Clone a graph. space.
USEUSE <graph_space_name>USE space1Specifies a graph space as the current working graph space for subsequent queries.
SHOW SPACESSHOW SPACESSHOW SPACESLists all the graph spaces in the NebulaGraph examples.
DESCRIBE SPACEDESC[RIBE] SPACE <graph_space_name>DESCRIBE SPACE basketballplayerReturns the information about the specified graph space.
CLEAR SPACECLEAR SPACE [IF EXISTS] <graph_space_name>Deletes the vertices and edges in a graph space, but does not delete the graph space itself and the schema information.
DROP SPACEDROP SPACE [IF EXISTS] <graph_space_name>DROP SPACE basketballplayerDeletes everything in the specified graph space.

TAG statements

StatementSyntaxExampleDescription
CREATE TAGCREATE TAG [IF NOT EXISTS] <tag_name> ( <prop_name> <data_type> [NULL | NOT NULL] [DEFAULT <default_value>] [COMMENT '<comment>'] [{, <prop_name> <data_type> [NULL | NOT NULL] [DEFAULT <default_value>] [COMMENT '<comment>']} ...] ) [TTL_DURATION = <ttl_duration>] [TTL_COL = <prop_name>] [COMMENT = '<comment>'] CREATE TAG woman(name string, age int, married bool, salary double, create_time timestamp) TTL_DURATION = 100, TTL_COL = "create_time"Creates a tag with the given name in a graph space.
DROP TAGDROP TAG [IF EXISTS] <tag_name>DROP TAG test;Drops a tag with the given name in the current working graph space.
ALTER TAGALTER TAG <tag_name> <alter_definition> [, alter_definition] ...] [ttl_definition [, ttl_definition] ... ] [COMMENT = '<comment>']ALTER TAG t1 ADD (p3 int, p4 string)Alters the structure of a tag with the given name in a graph space. You can add or drop properties, and change the data type of an existing property. You can also set a TTL (Time-To-Live) on a property, or change its TTL duration.
SHOW TAGSSHOW TAGSSHOW TAGSShows the name of all tags in the current graph space.
DESCRIBE TAGDESC[RIBE] TAG <tag_name>DESCRIBE TAG playerReturns the information about a tag with the given name in a graph space, such as field names, data type, and so on.
DELETE TAGDELETE TAG <tag_name_list> FROM <VID>DELETE TAG test1 FROM "test"Deletes a tag with the given name on a specified vertex.

Edge type statements

StatementSyntaxExampleDescription
CREATE EDGECREATE EDGE [IF NOT EXISTS] <edge_type_name> ( <prop_name> <data_type> [NULL | NOT NULL] [DEFAULT <default_value>] [COMMENT '<comment>'] [{, <prop_name> <data_type> [NULL | NOT NULL] [DEFAULT <default_value>] [COMMENT '<comment>']} ...] ) [TTL_DURATION = <ttl_duration>] [TTL_COL = <prop_name>] [COMMENT = '<comment>'] CREATE EDGE e1(p1 string, p2 int, p3 timestamp) TTL_DURATION = 100, TTL_COL = "p2"Creates an edge type with the given name in a graph space.
DROP EDGEDROP EDGE [IF EXISTS] <edge_type_name>DROP EDGE e1Drops an edge type with the given name in a graph space.
ALTER EDGEALTER EDGE <edge_type_name> <alter_definition> [, alter_definition] ...] [ttl_definition [, ttl_definition] ... ] [COMMENT = '<comment>']ALTER EDGE e1 ADD (p3 int, p4 string)Alters the structure of an edge type with the given name in a graph space.
SHOW EDGESSHOW EDGESSHOW EDGESShows all edge types in the current graph space.
DESCRIBE EDGEDESC[RIBE] EDGE <edge_type_name>DESCRIBE EDGE followReturns the information about an edge type with the given name in a graph space, such as field names, data type, and so on.

Vertex statements

StatementSyntaxExampleDescription
INSERT VERTEXINSERT VERTEX [IF NOT EXISTS] [tag_props, [tag_props] ...] VALUES <vid>: ([prop_value_list])INSERT VERTEX t2 (name, age) VALUES "13":("n3", 12), "14":("n4", 8)Inserts one or more vertices into a graph space in NebulaGraph.
DELETE VERTEXDELETE VERTEX <vid> [, <vid> ...]DELETE VERTEX "team1"Deletes vertices and the related incoming and outgoing edges of the vertices.
UPDATE VERTEXUPDATE VERTEX ON <tag_name> <vid> SET <update_prop> [WHEN <condition>] [YIELD <output>]UPDATE VERTEX ON player "player101" SET age = age + 2 Updates properties on tags of a vertex.
UPSERT VERTEXUPSERT VERTEX ON <tag> <vid> SET <update_prop> [WHEN <condition>] [YIELD <output>]UPSERT VERTEX ON player "player667" SET age = 31The UPSERT statement is a combination of UPDATE and INSERT. You can use UPSERT VERTEX to update the properties of a vertex if it exists or insert a new vertex if it does not exist.

Edge statements

StatementSyntaxExampleDescription
INSERT EDGEINSERT EDGE [IF NOT EXISTS] <edge_type> ( <prop_name_list> ) VALUES <src_vid> -> <dst_vid>[@<rank>] : ( <prop_value_list> ) [, <src_vid> -> <dst_vid>[@<rank>] : ( <prop_value_list> ), ...]INSERT EDGE e2 (name, age) VALUES "11"->"13":("n1", 1)Inserts an edge or multiple edges into a graph space from a source vertex (given by src_vid) to a destination vertex (given by dst_vid) with a specific rank in NebulaGraph.
DELETE EDGEDELETE EDGE <edge_type> <src_vid> -> <dst_vid>[@<rank>] [, <src_vid> -> <dst_vid>[@<rank>] ...]DELETE EDGE serve "player100" -> "team204"@0Deletes one edge or multiple edges at a time.
UPDATE EDGEUPDATE EDGE ON <edge_type> <src_vid> -> <dst_vid> [@<rank>] SET <update_prop> [WHEN <condition>] [YIELD <output>]UPDATE EDGE ON serve "player100" -> "team204"@0 SET start_year = start_year + 1Updates properties on an edge.
UPSERT EDGEUPSERT EDGE ON <edge_type> <src_vid> -> <dst_vid> [@rank] SET <update_prop> [WHEN <condition>] [YIELD <properties>]UPSERT EDGE on serve "player666" -> "team200"@0 SET end_year = 2021The UPSERT statement is a combination of UPDATE and INSERT. You can use UPSERT EDGE to update the properties of an edge if it exists or insert a new edge if it does not exist.

Index

  • Native index

    You can use native indexes together with LOOKUP and MATCH statements.

    StatementSyntaxExampleDescription
    CREATE INDEXCREATE {TAG | EDGE} INDEX [IF NOT EXISTS] <index_name> ON {<tag_name> | <edge_name>} ([<prop_name_list>]) [COMMENT = '<comment>']CREATE TAG INDEX player_index on player()Add native indexes for the existing tags, edge types, or properties.
    SHOW CREATE INDEXSHOW CREATE {TAG | EDGE} INDEX <index_name>show create tag index index_2Shows the statement used when creating a tag or an edge type. It contains detailed information about the index, such as its associated properties.
    SHOW INDEXESSHOW {TAG | EDGE} INDEXESSHOW TAG INDEXESShows the defined tag or edge type indexes names in the current graph space.
    DESCRIBE INDEXDESCRIBE {TAG | EDGE} INDEX <index_name>DESCRIBE TAG INDEX player_index_0Gets the information about the index with a given name, including the property name (Field) and the property type (Type) of the index.
    REBUILD INDEXREBUILD {TAG | EDGE} INDEX [<index_name_list>]REBUILD TAG INDEX single_person_indexRebuilds the created tag or edge type index. If data is updated or inserted before the creation of the index, you must rebuild the indexes manually to make sure that the indexes contain the previously added data.
    SHOW INDEX STATUSSHOW {TAG | EDGE} INDEX STATUSSHOW TAG INDEX STATUSReturns the name of the created tag or edge type index and its status.
    DROP INDEXDROP {TAG | EDGE} INDEX [IF EXISTS] <index_name>DROP TAG INDEX player_index_0Removes an existing index from the current graph space.
  • Full-text index

    SyntaxExampleDescription
    SIGN IN TEXT SERVICE [(<elastic_ip:port> [,<username>, <password>]), (<elastic_ip:port>), ...]SIGN IN TEXT SERVICE (127.0.0.1:9200)The full-text indexes is implemented based on Elasticsearch. After deploying an Elasticsearch cluster, you can use the SIGN IN statement to log in to the Elasticsearch client.
    SHOW TEXT SEARCH CLIENTSSHOW TEXT SEARCH CLIENTSShows text search clients.
    SIGN OUT TEXT SERVICESIGN OUT TEXT SERVICESigns out to the text search clients.
    CREATE FULLTEXT {TAG | EDGE} INDEX <index_name> ON {<tag_name> | <edge_name>} (<prop_name> [,<prop_name>]...) [ANALYZER="<analyzer_name>"]CREATE FULLTEXT TAG INDEX nebula_index_1 ON player(name)Creates full-text indexes.
    SHOW FULLTEXT INDEXESSHOW FULLTEXT INDEXESShow full-text indexes.
    REBUILD FULLTEXT INDEXREBUILD FULLTEXT INDEXRebuild full-text indexes.
    DROP FULLTEXT INDEX <index_name>DROP FULLTEXT INDEX nebula_index_1Drop full-text indexes.
    LOOKUP ON {<tag> | <edge_type>} WHERE ES_QUERY(<index_name>, "<text>") YIELD <return_list> [| LIMIT [<offset>,] <number_rows>]LOOKUP ON player WHERE ES_QUERY(fulltext_index_1,"Chris") YIELD id(vertex)Use query options.

Subgraph and path statements

TypeSyntaxExampleDescription
GET SUBGRAPHGET SUBGRAPH [WITH PROP] [<step_count> {STEP|STEPS}] FROM {<vid>, <vid>...} [{IN | OUT | BOTH} <edge_type>, <edge_type>...] YIELD [VERTICES AS <vertex_alias>] [,EDGES AS <edge_alias>] GET SUBGRAPH 1 STEPS FROM "player100" YIELD VERTICES AS nodes, EDGES AS relationshipsRetrieves information of vertices and edges reachable from the source vertices of the specified edge types and returns information of the subgraph.
FIND PATHFIND { SHORTEST | ALL | NOLOOP } PATH [WITH PROP] FROM <vertex_id_list> TO <vertex_id_list> OVER <edge_type_list> [REVERSELY | BIDIRECT] [<WHERE clause>] [UPTO <N> {STEP|STEPS}] YIELD path as <alias> [| ORDER BY $-.path] [| LIMIT <M>]FIND SHORTEST PATH FROM "player102" TO "team204" OVER * YIELD path as pFinds the paths between the selected source vertices and destination vertices. A returned path is like (<vertex_id>)-[:<edge_type_name>@<rank>]->(<vertex_id).

Query tuning statements

TypeSyntaxExampleDescription
EXPLAINEXPLAIN [format="row" | "dot"] <your_nGQL_statement>EXPLAIN format="row" SHOW TAGS
EXPLAIN format="dot" SHOW TAGS
Helps output the execution plan of an nGQL statement without executing the statement.
PROFILEPROFILE [format="row" | "dot"] <your_nGQL_statement>PROFILE format="row" SHOW TAGS
PROFILE format="dot" SHOW TAGS
Executes the statement, then outputs the execution plan as well as the execution profile.

Operation and maintenance statements

  • SUBMIT JOB BALANCE

    SyntaxDescription
    BALANCE LEADERStarts a job to balance the distribution of all the storage leaders in graph spaces. It returns the job ID.
  • Job statements

    SyntaxDescription
    SUBMIT JOB COMPACTTriggers the long-term RocksDB compact operation.
    SUBMIT JOB FLUSHWrites the RocksDB memfile in the memory to the hard disk.
    SUBMIT JOB STATSStarts a job that makes the statistics of the current graph space. Once this job succeeds, you can use the SHOW STATS statement to list the statistics.
    SHOW JOB <job_id>Shows the information about a specific job and all its tasks in the current graph space. The Meta Service parses a SUBMIT JOB request into multiple tasks and assigns them to the nebula-storaged processes.
    SHOW JOBSLists all the unexpired jobs in the current graph space.
    STOP JOBStops jobs that are not finished in the current graph space.
    RECOVER JOBRe-executes the failed jobs in the current graph space and returns the number of recovered jobs.
  • Kill queries

    SyntaxExampleDescription
    KILL QUERY (session=<session_id>, plan=<plan_id>)KILL QUERY(SESSION=1625553545984255,PLAN=163)Terminates the query being executed, and is often used to terminate slow queries.
  • Kill sessions

    SyntaxExampleDescription
    KILL {SESSION|SESSIONS} <SessionId>KILL SESSION 1672887983842984Terminates a single session.
    SHOW SESSIONS | YIELD $-.SessionId AS sid [WHERE <filter_clause>] | KILL {SESSION|SESSIONS} $-.sid`SHOW SESSIONSYIELD .SessionIdASsid,-.SessionId AS sid, -.CreateTime as CreateTime
    `SHOW SESSIONSKILL SESSIONS $-.SessionId``SHOW SESSIONS