Skip to content
Developer Edition runs on one host and does not require a product license file. Need multi-host deployment or performance testing at scale? Explore Enterprise Edition

GQL Cheat Sheet

This topic catalogs the most commonly used statements and commands in GQL for quick reference.

Note

The statements and commands in this topic are primarily based on the movie dataset. For brevity, the USE movie clause is omitted in most data query statements.

Data Definition Statements

Schema

Statement Description
CREATE SCHEMA IF NOT EXISTS /movie
Creates a schema.
DROP SCHEMA IF EXISTS /movie
Drops a schema.

Graph Type

Statement Description
'''
CREATE GRAPH TYPE IF NOT EXISTS movie_type AS { 
    NODE Actor (LABEL Person {id INT64, name STRING, birthDate DATE, PRIMARY KEY (id)}) , 
    NODE Director (LABEL Person {id INT64, name STRING, birthDate DATE, PRIMARY KEY (id)}), 
    NODE `User` (LABEL Person {id INT64 PRIMARY KEY}), 
    NODE Movie (LABEL Movie {id INT64 PRIMARY KEY, name STRING}), 
    NODE Genre (LABEL Genre {id INT64 PRIMARY KEY, name STRING}), 
    EDGE Act (Actor)-[:Act]->(Movie), 
    EDGE Direct (Director)-[:Direct]->(Movie), 
    EDGE Watch (`User`)-[:Watch {rate FLOAT}]->(Movie), 
    EDGE WithGenre (Movie)-[:WithGenre]->(Genre) }
'''   
Creates a graph type where each node type uses a single property as the primary key.
''' 
CREATE GRAPH TYPE IF NOT EXISTS social_network AS { 
    NODE Person (LABEL Person {id INT64 PRIMARY KEY, name STRING}), 
    NODE Company (LABEL Company {id INT64 PRIMARY KEY, name STRING}), 
    EDGE WorkAt (Person)-[:WorkAt {`from` DATE, to DATE, MULTIEDGE KEY ()}]->(Company), 
    EDGE Friend (Person)-[:Friend {since DATE MULTIEDGE KEY }]->(Person) }
'''   
Creates a graph type where each edge type uses a single property as the multi-edge key.
'''
CREATE GRAPH TYPE IF NOT EXISTS social_network_2 AS { 
    NODE Person (LABEL Person {id INT64 PRIMARY KEY, name STRING DEFAULT 'unknown', age INT32 DEFAULT 0}), 
    NODE Company (LABEL Company {id INT64 PRIMARY KEY, name STRING}) }
'''   
Creates a graph type where node type properties have default values.
'''
CREATE GRAPH TYPE IF NOT EXISTS primary_key_multi_properties AS { 
    NODE Person (LABEL Person {id INT64, name STRING, PRIMARY KEY (id, name)}), 
    EDGE Know (Person)-[:`Like` {`from` DATE, to DATE, MULTIEDGE KEY (`from`,to)}]->(Person) }
'''   
Creates a graph type where the primary key and multi-edge key each consist of multiple properties.
CREATE GRAPH TYPE IF NOT EXISTS empty_graph_type AS {}
Creates an empty graph type.
DROP GRAPH TYPE movie_type
Drops a graph type.
'''
ALTER GRAPH TYPE movie_type { 
    ADD NODE TYPE Company (LABEL Company {id INT PRIMARY KEY, name STRING}), 
    ADD EDGE TYPE Serve (Director)-[LABEL Serve{start_year INT, end_year INT}]->(Company) }
'''   
Adds node types and edge types.
'''
ALTER GRAPH TYPE movie_type { 
    DROP NODE TYPE Company, 
    DROP EDGE TYPE Serve }
'''   
Drops node types and edge types.
'''
ALTER GRAPH TYPE movie_type { 
    RENAME NODE TYPE Actor TO Actor_renamed, 
    RENAME EDGE TYPE Act TO Act_renamed }
'''   
Renames node types and edge types.
'''
ALTER GRAPH TYPE movie_type { 
    ALTER NODE TYPE `User` ADD LABELS Male&Above30,
    ALTER EDGE TYPE Watch ADD LABELS InCinema&AtHome }
'''   
Adds labels to node types and edge types.
'''
ALTER GRAPH TYPE movie_type { 
    ALTER NODE TYPE `User` DROP LABELS Male&Above30,
    ALTER EDGE TYPE Watch DROP LABELS InCinema&AtHome }
'''   
Drops labels from node types and edge types.
'''
ALTER GRAPH TYPE movie_type { 
    ALTER NODE TYPE `User` ADD PROPERTIES {email STRING, age INT64}, 
    ALTER EDGE TYPE Watch ADD PROPERTIES {`count` INT64, platform STRING} }
'''   
Adds properties to node types and edge types.
'''
ALTER GRAPH TYPE movie_type { 
    ALTER NODE TYPE `User` DROP PROPERTIES {email, age}, 
    ALTER EDGE TYPE Watch DROP PROPERTIES {`count`, platform} }
'''   
Drops properties from node types and edge types.
'''
ALTER GRAPH TYPE movie_type { 
    ALTER NODE TYPE Director RENAME PROPERTIES {birthDate TO birth, name TO lastName }, 
    ALTER EDGE TYPE Watch RENAME PROPERTIES {`rate` TO rating} }
'''   
Renames properties of node types and edge types.
'''      
ALTER GRAPH TYPE movie_type { 
    ALTER NODE TYPE Director MODIFY PROPERTIES {name STRING DEFAULT "Alex", birthDate DATE DEFAULT date("2016-09-20") },
    ALTER EDGE TYPE Watch MODIFY PROPERTIES {rate FLOAT DEFAULT 4.5} }
'''   
Modifies properties of node types and edge types.
RENAME GRAPH TYPE movie_type TO movie_type_renamed
Renames a graph type.

Graph

Statement Description
CREATE GRAPH IF NOT EXISTS movie TYPED movie_type
Creates a graph.
DROP GRAPH movie
Drops a graph.
RENAME GRAPH movie TO movie_renamed
Renames a graph.

Temporary Graph

Statement Description
CREATE TEMPORARY GRAPH IF NOT EXISTS #movie_temporary_graph AS COPY OF movie
Creates a temporary graph based on an existing graph.
CREATE TEMPORARY GRAPH IF NOT EXISTS #movie_temporary_graph_3 AS COPY OF GRAPH { USE movie MATCH (v) RETURN v }
Creates a temporary graph based on a subgraph.
DROP TEMPORARY GRAPH IF EXISTS #movie_temporary_graph
Drops a temporary graph.

Index

Statement Description
USE movie CREATE NORMAL INDEX IF NOT EXISTS idx_actor_age ON NODE Actor ( birthDate ASC )
Creates a normal index on a node type.
USE movie CREATE NORMAL INDEX IF NOT EXISTS idx_watch_rating ON EDGE Watch ( rate DESC )
Creates a normal index on an edge type.
'''
USE ann_test_graph CREATE VECTOR INDEX ann_node_ivf_l2 ON NODE N1&N2::vec1
      OPTIONS {DIM: 3, METRIC: L2, TYPE: IVF, NLIST: 10, TRAINSIZE: 4 }
'''   
Creates an IVF vector index based on the L2 metric on two node types.
'''
USE ann_test_graph CREATE VECTOR INDEX ann_edge_hnsw_ip ON EDGE E1::vec1 
      OPTIONS {DIM: 3, METRIC: IP, TYPE: HNSW, MAXDEGREE: 3, EFCONSTRUCTION: 6, CAPACITY: 500
'''   
Creates an HNSW vector index based on the IP metric on an edge type.
USE my_graph CREATE SPATIAL INDEX IF NOT EXISTS idx_gnode_g ON NODE Person(any_geo, s2_max_level = 30, s2_max_cells = 8)
Creates a spatial index on a geospatial property of a node type.
USE my_graph CREATE SPATIAL INDEX IF NOT EXISTS idx_gedge_g ON EDGE GEdge(company_location, s2_max_level = 30, s2_max_cells = 8)
Creates a spatial index on a geospatial property of an edge type.
USE movie CREATE FULLTEXT INDEX IF NOT EXISTS ft_movie ON NODE Movie(name)
Creates a full-text index on a node type.
USE movie DROP INDEX IF EXISTS idx_actor_age
Drops an index on a node type.
USE movie DROP INDEX IF EXISTS idx_watch_rating
Drops an index on an edge type.

TTL

Statement Description
USE movie CREATE TTL ON EDGE Watch(ttl_test) duration({days:1, hours:2, minutes:3, seconds:4, milliseconds:5, microseconds:6})
Sets the TTL duration for an edge type.
USE movie DROP TTL ON EDGE Watch
Removes the TTL duration for an edge type.
USE movie ALTER TTL ON EDGE Watch(ttl_test) duration({seconds:4, milliseconds:5, microseconds:6})
Modifies the TTL duration for an edge type.

Procedure

Statement Description
CREATE PROCEDURE test(a INT, b STRING) RETURNS (x INT, y STRING) AS { RETURN a, b }
Creates a UDP.
CREATE OR REPLACE PROCEDURE test1() RETURNS ret INT COMMENT 'test function 1' AS { RETURN 2 }
Creates or replaces a UDP.
DROP PROCEDURE IF EXISTS test(INT, STRING)
Drops a UDP.
ALTER PROCEDURE test(INT, STRING) COMMENT 'test_comment'
Modifies the comment of a UDP.
ALTER PROCEDURE test(INT, STRING) RENAME TO test44
Renames a UDP.

Data Manipulation Statements

INSERT

Statement Description
'''
INSERT (@Director{id:11, name:"Alice", birthDate:date("1990-01-01")}), 
       (TYPED Actor{id:22, name:"Bob", birthDate:date("1990-01-02")})
'''   
Inserts nodes based on node types. If a conflict is detected, the statement fails and reports an error, and no graph elements are inserted.
INSERT OR REPLACE (@Director{id:11, name:"Alice2"})
With INSERT OR REPLACE, inserts the graph element if it does not exist, or replaces it if it already exists.
'''
INSERT OR IGNORE (@Director{id:11, name:"Alice3", birthDate:date("1990-06-30")}),
                 (@Director{id:12, name:"Carol", birthDate:date("1991-01-01")})
'''
With INSERT OR IGNORE, inserts the graph element if it does not exist. If it already exists, ignores the write and keeps the existing data unchanged without reporting an error. In this example, the existing node with id:11 remains unchanged, and the node with id:12 is inserted if it does not yet exist.
INSERT OR UPDATE (@Director{id:11, name:"Alice4", birthDate:date("1990-12-31")})
With INSERT OR UPDATE, inserts the graph element if it does not exist, or updates it if it already exists.
'''
INSERT (:Movie{id:10000,name:"movie"}), 
       (IS Genre{id:11000,name:"genre"})
'''    
Inserts nodes by specifying labels.
INSERT (@Movie{id:10002,name:NULL})
Inserts a node with a NULL property value.
'''
MATCH (n:Movie{id:10000}), (m@User{id:1})
INSERT (n)<-[:Watch{rate:5}]-(m)
'''   
Inserts an edge based on existing nodes.
INSERT (@Actor{id:200000,name:"actor", birthDate:date("1990-01-01")}) -[@Act]-> (@Movie{id:10003,name:"movie1"})
Inserts new nodes and edges simultaneously.
'''
MATCH (n@Movie{id:10000}) 
INSERT (n)<-[@Watch{rate:5}]-(@User{id:11002})
'''   
Inserts a node and an edge based on an existing node.
'''
MATCH (n@User{id:1}) 
INSERT (n)-[@Watch{rate:5}]->(m@Movie{id:10004,name:"movie2"}),
       (m)-[@WithGenre]->(@Genre{id:11003,name:"genre3"})
'''   
Inserts multiple nodes and edges based on existing nodes.
'''
TABLE t { actor_id, movie_id, movie_name } =  
    ( 2, 20001, 'Movie1' ),  
    ( 3, 20002, 'Movie2' ),  
    ( 4, 20003, 'Movie3' )  
USE movie 
FOR re IN t 
MATCH (a@Actor) WHERE a.id = re.actor_id 
INSERT (a)-[@Act]->(@Movie {id: re.movie_id, name: re.movie_name})
'''   
Batch inserts nodes and edges using a table variable.

SET

Statement Description
MATCH (v@Actor{name:"Mark Hamill"}) SET v.name="Mark Hamill2"
Updates a single property of a node.
MATCH (v@Actor{name:"Mark Hamill"}) SET v.name="Mark Hamill2", v.birthDate=date("1951-09-26")
Updates multiple properties of a node.
MATCH(v1@`User`{id:414})-[e@Watch]->(v2@Movie{name:"Star Trek: The Motion Picture"}) SET e.rate=4.0
Updates a single property of an edge.
'''
TABLE t { id, new_name } =  
    ( 10001, 'Alice_renamed' ),  
    ( 10002, 'Bob_renamed' ),  
    ( 10003, 'Charlie_renamed' )  
USE movie 
FOR re IN t 
MATCH (a@Actor) WHERE a.id = re.id 
SET a.name = re.new_name
'''   
Batch updates nodes using a table variable.

DELETE

Statement Description
MATCH (a@Actor{id:10000}) DELETE a
Deletes a node.
'''
MATCH (a@Actor{name:"Mila Parély"})-[e@Act]->(b@Movie{name:"Beauty and the Beast"}) 
DELETE e
'''   
Deletes an edge.
'''
MATCH (a@Actor{name:"Nane Germon"})-[e@Act]->(b@Movie{name:"Beauty and the Beast"}) 
DELETE a, e
'''   
Deletes a node and an edge.
'''
MATCH (a@Actor{name:"Josette Day"}) 
DETACH DELETE a
'''   
Uses DETACH DELETE to delete a node and all edges connected to it.
MATCH (a) DETACH DELETE a
Uses DETACH DELETE to delete all nodes and edges.
'''
TABLE t { id } =  
    ( 10001 ),  
    ( 10002 ),  
    ( 10003 )  
USE movie 
FOR re IN t 
MATCH (a@Actor) WHERE a.id = re.id 
DETACH DELETE a
'''   
Batch deletes nodes using a table variable.

Data Query Statements

MATCH

Statement Description
MATCH (v) RETURN v LIMIT 5
Matches nodes with a node variable.
MATCH (v:Person) RETURN v LIMIT 5
Matches nodes with a label.
VALUE s = "Person"
MATCH (v:s) WHERE v.id = 1 RETURN v.id, type(v)
Matches nodes with a variable label.
'''
MATCH (v:Person) WHERE v.birthDate > date("1990-01-20") 
RETURN v LIMIT 5
'''   
Matches nodes with a WHERE clause.
MATCH (v {id:199}) RETURN v
Matches nodes with node properties.
MATCH (v@Actor) RETURN v LIMIT 5
Matches nodes with a single node type.
VALUE s = "Director"
MATCH (v@[s,"User"]) WHERE v.id = 1 RETURN v.id, type(v)
Matches nodes with variable node types.
MATCH (v@[Actor,Director]) RETURN v LIMIT 5
Matches nodes with multiple node types.
MATCH ()-[e]->() RETURN e LIMIT 5
Matches edges with an edge variable.
MATCH ()-[e:Act]->() RETURN e LIMIT 5
Matches edges with a label.
VALUE et = "Direct"
MATCH (src:Person)-[e:et]->(dst) WHERE src.id = 1 RETURN type(src), type(e), type(dst)
Matches edges with a variable label.
MATCH ()-[e:Watch]->() WHERE e.rate > 4 RETURN e LIMIT 5
Matches edges with a WHERE clause.
MATCH ()-[e {rate: 4}]->() RETURN e LIMIT 5
Matches edges with edge properties.
MATCH ()-[e@Watch]->() RETURN e LIMIT 5
Matches edges with a single edge type.
VALUE et = "Direct"
MATCH (src:Person)-[e@et]->(dst) WHERE src.id = 1 RETURN type(src), type(e), type(dst)
Matches edges with a variable edge type.
MATCH ()-[e@[Direct,Watch]]->() RETURN e LIMIT 5
Matches edges with multiple edge types.
MATCH (a:Genre)<-[e:WithGenre]-(b:Movie) RETURN a LIMIT 3
Matches incoming edges.
MATCH (a:Person)~[e:Act]~(b:Movie) RETURN e LIMIT 3
Matches undirected edges.
MATCH (a:Genre)<~[e:WithGenre]~(b:Movie) RETURN a,b LIMIT 3
Matches undirected edges and incoming edges.
MATCH (a:Movie)<-[e]->(b) RETURN a,b,e LIMIT 3
Matches outgoing and incoming edges.
MATCH (a:Movie)-[e]-(b) RETURN e,a,b LIMIT 3
Matches edges in any direction.
MATCH (a{id:1})-[e]->{1,2}(b:Genre) RETURN labels(a)
Matches variable-length paths with a quantified edge pattern.
MATCH (v1)-[e:Watch]->(v2) RETURN v1,v2 LIMIT 3
Matches with a simple path pattern.
MATCH (v1)-[e1]->(v2)-[e2]->(v3:Genre) RETURN v3 LIMIT 5
Matches with a complex path pattern.
MATCH (a{id:1})(()-[e]->()){1,2}(b:Genre) RETURN labels(a)
Matches variable-length paths with a quantified path pattern.
MATCH p = (a{id:1})((n)-[e]->(m WHERE m.id > 1000)){1,2}(b:Genre) RETURN p
Matches variable-length paths and returns the paths.
MATCH p = TRAIL (a@Actor)-[e:Act]->{1,3}(b:Movie) RETURN p LIMIT 3
Matches paths without repeated edges.
MATCH p = ACYCLIC (a@Actor)-[e:Act]->{1,3}(b:Movie) RETURN p LIMIT 3
Matches paths without repeated nodes.
MATCH p = ALL (a@Actor{id:134060})-[e:Act]-{1,3}(b:Movie) RETURN p
Matches all paths between two nodes that satisfy the conditions.
MATCH p= ANY 2 (a@Actor{id:134060})-[e:Act]-{1,3}(b:Movie) RETURN p
Matches any two paths between two nodes that satisfy the conditions.
MATCH p = ALL SHORTEST (a@Actor{id:134060})-[e:Act]-{1,3}(b:Movie) RETURN p
Matches all shortest paths between two nodes that satisfy the conditions.
MATCH p= ANY SHORTEST (a@Actor{id:134060})-[e:Act]-{1,3}(b:Movie) RETURN p
Matches any single shortest path between two nodes that satisfy the conditions.
MATCH p= SHORTEST 2 (a@Actor{id:134060})-[e:Act]-{1,3}(b:Movie) RETURN p
Matches any two shortest paths between two nodes that satisfy the conditions.
'''
MATCH (a@Actor),(b@Movie)
WHERE EXISTS {(a)-[:Act]->(b)}
RETURN a.name, b.name LIMIT 3
'''   
Matches multiple node patterns.
'''
MATCH ()-[e1:Watch]->(b), (c)-[e2:WithGenre]->()
WHERE b.id = c.id AND e1.rate >= 4
RETURN DISTINCT b.name, e1.rate  LIMIT 5
'''   
Matches multiple edge patterns.
MATCH p1 = (a:Person{id:5498})-[e1:Act]->(b), p2= (b)-[e2:WithGenre]->(d) RETURN p1, p2
Matches multiple path patterns.
OPTIONAL MATCH (v:NotExistLabel) RETURN v
Specifies the OPTIONAL keyword for optional matching.
'''
MATCH (b:Genre{id:87}) 
OPTIONAL MATCH p = (a:Movie{id:2000})-[e]->(b) 
RETURN b, p
'''   
Uses both regular matching and optional matching.

FILTER

Statement Description
FOR i IN LIST[1, 2, 3] FILTER i>2 RETURN i
Filters the results of a FOR statement.
'''
MATCH (v:Person) FILTER v.birthDate > date("1990-01-20") 
RETURN v ORDER BY v.birthDate LIMIT 3
'''   
Filters the results of a MATCH statement.
'''
CALL show_graphs() YIELD name 
FILTER name = "movie" RETURN *
'''   
Filters the results of a CALL statement.

LET

Statement Description
'''
LET a = 1 + 2, b = 3 + 4  LET c = a + b 
RETURN a, b, c
'''   
Defines variables using expressions.
'''
MATCH (v@Actor) WHERE v.id = 199 
LET a = v.name, b = upper(a) RETURN b
'''   
Defines variables using node properties.
LET a = VALUE { USE movie MATCH (v@Actor) WHERE v.id = 199 RETURN v.name LIMIT 1 } RETURN a
Defines a variable using a subquery.
'''
LET a = 199 RETURN a 
NEXT USE movie MATCH (v WHERE v.id = a) RETURN v
'''   
Uses variables in subsequent statements.

FOR

Statement Description
LET l = list[1, 2, 3] FOR e IN l RETURN e
Unnests a list.
'''
LET ll = list[list[1, 2, 3], list[4, 5, 6]] 
FOR l IN ll 
FOR e IN l 
RETURN e
'''   
Unnests a nested list.
'''
LET l1 = list[1, 2, 3], l2 = list[4, 5, 6] 
FOR e1 IN l1 
FOR e2 IN l2 
RETURN e1, e2
'''   
Unnests two lists.
'''
MATCH p = (v@Actor)-[]->(f@Movie{name:"Wilbur Wants to Kill Himself"})-[]->(g@Genre) 
LET sz = length(p), vid = v.id, l = range(1, length(p)) 
FOR e IN l 
RETURN DISTINCT sz, vid, l, e 
ORDER BY vid LIMIT 6 
'''   
Unnests a list generated by the range function.
'''
LET l1 = list[1, 2, 3], l2 = trim(list[4, 5, 6, 7], 2) 
FOR e IN l1 || l2 
RETURN e
'''   
Unnests two lists concatenated with ||.
'''
TABLE t { id, name, birthDate } =  
    ( 10001, 'Alice', DATE '1990-01-01' ),  
    ( 10002, 'Bob', DATE '1991-02-02' ),  
    ( 10003, 'Charlie', DATE '1992-03-03' ) 
FOR e IN t 
RETURN e.id, e.name, e.birthDate
'''   
Unnests a table.
'''
LET l=list[10, 20, 30] 
FOR e IN l WITH ORDINALITY idx 
RETURN e, idx
'''   
Unnests a list and returns the 1-based index.
'''
FOR i IN range(1, 10239) WITH OFFSET idx
RETURN i, idx
ORDER BY i ASC 
LIMIT 5
'''   
Unnests a list and returns the 0-based index.

Pagination

Statement Description
'''
FOR i IN LIST[3, 2, 5, 4, 1] 
ORDER BY i ASC 
OFFSET 1 
LIMIT 3 
RETURN i
'''   
Paginates using ORDER BY, OFFSET, and LIMIT.
'''
FOR i IN LIST[3, 2, 5, 4, 1] 
RETURN i 
OFFSET 1 
LIMIT 3
'''   
Paginates after the RETURN statement.

RETURN

Statement Description
MATCH (v:Person WHERE v.id = 107224) RETURN *
Returns all results.
MATCH (v:Person WHERE v.id = 107224) RETURN v.id, v.name, v.birthDate
Returns multiple properties of a node.
MATCH (v:Person WHERE v.id = 107224) RETURN v.id AS id, v.name AS name, v.birthDate AS birthDate
Returns multiple properties of a node with aliases.
'''
MATCH (v:Movie WHERE v.id = 172)<-[e:Watch]-()
RETURN v.name AS movie, avg(e.rate) AS average_score 
GROUP BY movie
'''   
Returns aggregated results.
MATCH (m:Movie)-[e:WithGenre]->(g:Genre)  
RETURN DISTINCT g.name AS Category LIMIT 5
Returns deduplicated results.

Primitive Result Statements

Statement Description
'''
MATCH (u@User)-[w:Watch]->(m:Movie)  
RETURN DISTINCT w.rate AS rate 
ORDER BY rate ASC OFFSET 2 Limit 4
'''   
Returns unique results with pagination.
MATCH (v) FINISH
Ends a MATCH statement without returning data.
'''
{MATCH (v:Person) 
CALL {MATCH (t) WHERE t.id = v.id FINISH} 
RETURN v.id AS a LIMIT 5}
'''   
Ends an inline procedure.

CALL

Statement Description
CALL show_graphs() RETURN *
Calls a named procedure.
'''
OPTIONAL CALL show_graphs() YIELD name AS gn 
CALL version() YIELD version AS v 
RETURN gn, v
'''   
Calls a named procedure with the OPTIONAL keyword.
''' 
LET x = 10, y = 20 
CALL { LET z = 30 RETURN x + y AS sum_xy, z * 2 AS double_z } 
RETURN *
'''   
Calls an inline procedure for computation.
'''
LET a = 1, b = 2 
OPTIONAL CALL { MATCH (v:Movie{id:1}) RETURN v.id AS id } 
RETURN *
'''   
Calls an inline procedure with the OPTIONAL keyword.

Linear Query

Statement Description
FOR i IN LIST[1, 2, 3] FILTER WHERE i>1 RETURN i OFFSET 1
Executes a linear query with FOR, FILTER, RETURN, and OFFSET statements.
'''
MATCH (v@`User`{id: 123})-[e:Watch]->(m:Movie) 
FILTER WHERE e.rate > 3 
RETURN m.name AS movie, e.rate AS rate 
ORDER BY rate DESC
'''   
Executes a linear query with MATCH, FILTER, RETURN, and ORDER BY statements.

Composite Query

Statement Description
'''
FOR i IN LIST[4,1,2,3,3] RETURN i UNION 
FOR i IN LIST[11,2,2,22,33,33] RETURN i ORDER BY i OFFSET 1 LIMIT 2
'''   
Combines two query results using the UNION operator.
'''
MATCH (v)-[:Watch]->(@Movie{id: 473}) RETURN v  EXCEPT  
MATCH (v)-[:Watch]->(@Movie{id: 648}) RETURN v
'''   
Combines two query results using the EXCEPT operator.
'''   
MATCH (v)-[:Watch]->(@Movie{id: 473}) RETURN v  INTERSECT  
MATCH (v)-[:Watch]->(@Movie{id: 648}) RETURN v
'''   
Combines two query results using the INTERSECT operator.

Nearest Neighbor Query

Statement Description
'''
USE ann_test_graph 
MATCH (v:N1|N2) 
ORDER BY euclidean(v.vec1, VECTOR<3,float>([1.0, 2.0, 3.0])) ASC
LIMIT 3 
RETURN v.id AS vid, labels(v) AS vlabel, v.vec1 AS vec1, euclidean(v.vec1, VECTOR<3,float>([1.0, 2.0, 3.0])) AS distance
'''   
Performs a KNN search to find the 3 nearest neighbors based on Euclidean distance.
'''
USE ann_test_graph 
MATCH (v:N1|N2) 
ORDER BY euclidean(v.vec1, VECTOR<3,float>([1.0, 2.0, 3.0])) ASC
APPROXIMATE 
LIMIT 3 
OPTIONS {TYPE: IVF, NPROBE: 256} 
RETURN v.id AS vid, labels(v) AS vlabel, v.vec1 AS vec1, euclidean(v.vec1, VECTOR<3,float>([1.0, 2.0, 3.0])) AS distance
'''   
Performs an ANN search to find the 3 nearest neighbors based on Euclidean distance.

Import/Export Statements

IMPORT

Statement Description
'''
USE #movie_import IMPORT INTO GRAPH { 
  GRAPH FROM NEBULA { 
  FORMAT: "NEBULA", 
  PATH: "nebula://root:<password>@<graph_host>:<graph_port>?graph=movie&schema=/default_schema"
  }  
}
'''
Imports a complete graph from NebulaGraph Database Developer Edition into a temporary graph.
'''
USE #movie_import_2 IMPORT INTO GRAPH 
{
  NODE (v@Actor{id:id, name:name}) FROM NEBULA { 
    FORMAT: "NEBULA", 
    PATH: "nebula://root:<password>@<graph_host>:<graph_port>?graph=movie&node_type=Actor"
  },
  NODE (v@Movie{id:id, name:name}) FROM NEBULA { 
    FORMAT: "NEBULA", 
    PATH: "nebula://root:<password>@<graph_host>:<graph_port>?graph=movie&node_type=Movie"
  },
  EDGE (id:id)-[e@Act{}]->(id:id) FROM NEBULA { 
    FORMAT: "NEBULA", 
    PATH: "nebula://root:<password>@<graph_host>:<graph_port>?graph=movie&edge_type=Act"
  }
}
'''
Imports specific nodes and edges from NebulaGraph Database Developer Edition into a temporary graph.
'''
USE #pagerank_graph IMPORT INTO GRAPH 
  { 
    NODE (v@Person {id: u_id, name: u_name}) FROM DATAFILE { 
        PATH: "file:///tmp/test/pagerank_node.csv", 
        FORMAT: "CSV", 
        DELIMITER: ',' 
    }, 
    EDGE (id: src_id, name: src_name)-[e@Knows{}]->(id: dst_id, name: dst_name) FROM DATAFILE { 
        PATH: "file:///tmp/test/pagerank_edge.csv", 
        FORMAT: "CSV", 
        DELIMITER: ',' 
    } 
  } OPTIONS {PRIMARY_KEY_AS_NODE_ID:false} 
'''
Imports data directly from a CSV file into a temporary graph.
'''
FILE node_file { id INT } = DATAFILE { 
    PATH:"file:///tmp/test/wcc_node.csv", 
    FORMAT:"CSV"
}
FILE edge_file { src INT, dst INT } = DATAFILE {
    PATH:"file:///tmp/test/wcc_edge.csv",
    FORMAT:"CSV"
}
USE #wcc_graph IMPORT INTO GRAPH { 
    NODE (v@Person {id: id}) FROM node_file, 
    EDGE (id: src)-[e@Knows{}]->(id: dst) FROM edge_file 
  }
'''
Imports data from a CSV file into a temporary graph using file variables.

EXPORT

Statement Description
'''
USE #movie_temporary_graph { 
   FILE f { nodes STRING, edges STRING } = DATAFILE {PATH:"file:///tmp/test", FORMAT:"CSV", INCLUDE_HEADER: true} 
   MATCH (v@`User`)-[e]-(m@Movie) WHERE e.rate = 5.0 AND v.id > 605 
   PER PATH { 
       EXPORT v, e INTO f
   } 
}
'''
Exports nodes and edges to a CSV file.
'''
USE #movie_temporary_graph { 
   FILE f { user_id INT, rate DOUBLE, movie_name STRING } = DATAFILE {PATH:"file:///tmp/test", FORMAT:"CSV", INCLUDE_HEADER: true} 
   MATCH (v@`User`)-[e]-(m@Movie) WHERE e.rate = 5.0 AND v.id > 605 
   PER PATH { 
       EXPORT v.id, e.rate, m.name INTO f
   } 
}
'''
Exports properties of nodes and edges to a CSV file.
'''
USE #movie_temporary_graph { 
   NODE VALUE a MaxAgg<INT> = 280000
   NODE VALUE b MinAgg<INT> = 280000
   TABLE t TYPED TABLE { original_id INT, maxed_id INT, mined_id INT } 
   MATCH (v@Actor) WHERE v.id > 271940 
   PER NODE (v) { 
       SET v.@a += v.id 
       SET v.@b += v.id
   } 
   MATCH (v@Actor) WHERE v.id > 271940 
   PER NODE (v) { 
       EXPORT v.id, v.@a, v.@b INTO t
   } 
   FOR r IN t 
   RETURN r.original_id AS original_id, r.maxed_id AS maxed_id, r.mined_id AS mined_id 
}
'''
Exports node-attached aggregator values to a table.

Server-side Programming Statements

Match-Compute Statement

Statement Description
'''
USE #match_compute_movie {
  /* ====== Declarations ====== */
  VALUE source_id = 1                          // Source user ID for similarity computation
  VALUE source_edges    SumAgg<INT64> = 0      // Movies liked by the source user
  VALUE topk_similarity TopKAgg<5, similarity DOUBLE DESC, id INT DESC>  // Top 5 similar users
  NODE VALUE target_edges SumAgg<INT64> = 0    // Movies liked by each user
  NODE VALUE intersection SumAgg<INT64> = 0    // Movies liked by both this user and the source user
  VALUE v_set ACTIVE_SET                       // Movies liked by the source user

  /* ====== Step 1: Count user movie preferences ====== */
  // Count movies liked by all users
  MATCH (u@User)-[e:Watch]->(m:Movie)
  PER PATH {
    SET u.@target_edges += 1                  // Increment the movie count for each user
  }

  /* ====== Step 2: Collect source user data ====== */
  // Process source user preferences
  MATCH (u@User)-[:Watch]->(m:Movie) 
  WHERE u.id = source_id  // Filter for the source user
  PER NODE (u) {
    SET @source_edges += u.@target_edges     // Store the source user movie count
  }
  FINALLY { SET v_set = m }                      // Populate the active set with the source user movies

  /* ====== Step 3: Compute user similarity ====== */
  // Find movies liked by both the source user and other users
  MATCH (m:Movie)<-[:Watch]-(t@User)
  WHERE t.id <> source_id AND m IN v_set                  // Exclude the source user and start from the source user movies
  PER PATH {
    SET t.@intersection += 1                 // Count shared movies
  }
  PER NODE (t) {
    // Compute the union of movies liked by the source user and each other user
    VALUE union_size = t.@target_edges + @source_edges - t.@intersection

    IF union_size <> 0 THEN {
      VALUE similarity = CAST(t.@intersection AS DOUBLE) / union_size

      // Store the result in the top-k aggregator
      SET @topk_similarity += RECORD{
        similarity: similarity, 
        id: t.id
      }
    }
  }

  /* ====== Step 4: Return results ====== */
  // Return the top 5 similar users
  FOR r IN @topk_similarity
    RETURN r.id AS user_id, 
          ROUND(r.similarity, 5) AS jaccard_similarity
}
'''
Computes the Jaccard similarity between users based on their movie preferences.

Variable Operation Statements

Statement Description
'''
USE #movie_temporary_graph { 
    VALUE a INT = 1 
    VALUE b INT = 1 
    VALUE c INT = 1 
    SET a = a + 1 
    SET b = a + 2 
    SET c = b + 3 
    RETURN a, b, c 
}
'''
Assigns values to primitive value variables.
'''
USE #movie_temporary_graph { 
    VALUE a SumAgg<INT> = 0
    VALUE b MaxAgg<DOUBLE> = 0.0
    VALUE c OrAgg = false 
    SET @a = 10 
    SET @b = 20.5 
    SET @c = true 
    RETURN @a, @b, @c 
}
'''
Assigns values to global aggregated value variables.
'''
USE #movie_temporary_graph { 
  NODE VALUE a ListAgg<INT>
  MATCH (v@Actor) WHERE v.id > 271940 
  PER NODE (v) { 
    SET v.@a = LIST[v.id] 
    LOG_INFO("ID_List: ", v.@a) 
  } 
}
'''
Assigns values to node-attached aggregator value variables.
'''
USE #movie_temporary_graph { 
    VALUE active_set ACTIVE_SET 
    VALUE list_id ListAgg<INT64>

    MATCH (a@Actor) WHERE a.id IN [31, 8252] 
    PER NODE (a) { 
        // Add the unique identifiers (UIDs) of matched nodes to the list
        SET @list_id += element_id(a)
    }
    // Assign the node UID list to the active set variable
    SET active_set = @list_id

    MATCH (a) 
    WHERE a IN active_set 
    PER NODE (a) { 
        LOG_INFO("Actor Name: ", a.name) 
    } 
}
'''
Assigns values to an active set variable.
'''
USE #movie_temporary_graph {
  VALUE global_avg AvgAgg<INT>
  SET @global_avg += 3     // Average: 3.0 (Total: 3, Count: 1)
  SET @global_avg += 7     // Average: 5.0 (Total: 10, Count: 2)
  SET @global_avg += 5     // Average: 5.0 (Total: 15, Count: 3)
  LOG_INFO("@global_avg: ",@global_avg)
}
'''
Aggregates values into a global aggregated value variable.
'''
USE #movie_temporary_graph {
  NODE VALUE node_avg AvgAgg<DOUBLE>

  MATCH (a@User WHERE a.id IN [1,3,4])-[w@Watch]->(b@Movie)
  PER PATH {
    // Accumulate user movie ratings and compute the average
    SET a.@node_avg += w.rate
  }
  PER NODE (a) {
    LOG_INFO("a.id: ",a.id, " a.@node_avg: ",a.@node_avg)
  }
}
'''
Aggregates values into a node-attached aggregator value variable.
'''
USE #movie_temporary_graph {
  VALUE global_set_1 SetAgg<INT>
  SET @global_set_1 += 3    // set: {3}
  SET @global_set_1 += 7    // set: {3, 7}  
  SET @global_set_1 += 3    // set: {3, 7} (duplicate ignored)
  SET @global_set_1 += 5    // set: {3, 7, 5}
  LOG_INFO("@global_set_1: ", @global_set_1)

  SET @global_set_1.clear() // set: {}
  LOG_INFO("@global_set_1: ", @global_set_1)
}
'''
Calls a member function of an aggregated value variable.

Control Flow Statements

Statement Description
'''
VALUE i INT = 0 
WHILE i < 5 THEN {
  SET i = i + 1 
} 
RETURN i
'''
Repeatedly executes a statement block using a WHILE loop.
'''
VALUE i INT = 4 
IF i < 3 THEN {
  SET i = i + 1 
} ELSEIF i < 5 THEN {
  SET i = i + 2 
} ELSE { 
  SET i = i - 1 
} 
RETURN i
'''
Conditionally executes a statement block using an IF-ELSEIF-ELSE statement.
'''
VALUE i INT = 0 
WHILE i < 5 THEN {
  IF i = 3 THEN { 
    BREAK 
    } 
  SET i = i + 1 
} 
RETURN i 
'''
Exits a loop using the BREAK statement.
'''
VALUE i INT = 0 
WHILE i < 5 THEN {
  IF i < 3 THEN {
    SET i = i + 1 
    CONTINUE 
  } ELSE { 
    SET i = i + 1 
  } 
} 
RETURN i
'''
Skips the remaining statements in the current iteration and proceeds to the next iteration using the CONTINUE statement.

Log Statement

Statement Description
'''
USE #movie_temporary_graph { 
  VALUE w SumAgg<INT> = 0
  MATCH ()-[e:Watch]-() 
  PER PATH { 
    SET @w += 1 
  } 
  LOG_INFO("Finish Iteration") 
  LOG_WARN("Final w: ", @w) 
  RETURN @w AS watch_count 
}
'''
Logs informational and warning messages during query execution.

Statement Blocks

Statement Description
'''
MATCH (a@Actor{id:2}) RETURN a 
NEXT INSERT (a)-[r@Act{}]->(b@Movie{id:2})
'''   
A statement block containing both data query and data manipulation statements.
'''
MATCH (actor@Actor)-[:Act]-(movie@Movie), 
(director@Director)-[:Direct]->(movie), (audience@`User`)-[:Watch]->(movie) 
RETURN DISTINCT audience, movie LIMIT 10 
NEXT LET valid=1 
RETURN sum(valid) AS audienceCount, movie GROUP BY movie
'''   
A statement block containing multiple data query statements.

Clauses

USE

Statement Description
'''
USE movie 
MATCH (n:Person WHERE n.id = 107224) 
RETURN n.name
'''   
Declares a working graph in a query statement.
'''
USE movie MATCH (n:Movie WHERE n.id = 363) RETURN n.name AS movie_name 
UNION 
USE movie_2 MATCH (n:Movie WHERE n.id = 302) RETURN n.name AS movie_name
'''   
Declares multiple working graphs in a composite query statement.
'''
USE movie 
MATCH (n@`User` WHERE n.id = 599)-[]->(m:Movie) RETURN n.id AS audience, m.name AS movie, VALUE { 
    USE movie 
    MATCH (c:Movie)<-[e:Watch]-() WHERE c.name =m.name RETURN avg(e.rate) AS average_rate GROUP BY ()
    } AS average_rate 
ORDER BY average_rate DESC 
LIMIT 10 
'''   
Declares a working graph multiple times in a nested query statement.
'''
USE movie 
INSERT (:Movie{id:10000,name:"movie"}), 
       (IS Genre{id:11000,name:"genre"})
'''   
Declares a working graph in a data manipulation statement.

WHERE

Statement Description
'''
MATCH (v:Movie)<-[e:Watch]-(u@`User`)
WHERE e.rate > 3 
RETURN v.name AS movie, u.id AS audience, e.rate AS rate 
LIMIT 10
'''   
Filters with a single condition.
'''
MATCH (v:Movie)<-[e:Watch]-(u@`User`)
WHERE e.rate > 2 AND u.id = 100 
RETURN v.name AS movie, e.rate AS rate 
LIMIT 10
'''   
Filters with multiple conditions.

YIELD

Statement Description
'''
CALL show_graphs() YIELD graph_type, name AS graph_name 
RETURN graph_type, graph_name
'''   
Selects and renames columns.

GROUP BY

Statement Description
'''
FOR i IN LIST[1,2,3,4,2,2] 
RETURN i, i+1 AS i_1, i+2 AS i_2, count(*) 
GROUP BY i
'''   
Groups by a single column.
'''
MATCH (a@Actor WHERE a.birthDate=date("1971-01-01")) 
RETURN a.birthDate as birthday, count(*) AS num 
GROUP BY birthday
'''   
Groups by an aliased column.
'''
MATCH (a@Actor) 
RETURN a.birthDate as birthday, a.name as name, count(*) AS num 
GROUP BY birthday, name 
LIMIT 10
'''   
Groups by multiple columns.
'''
FOR i in LIST[1,2,3,4,2,2] 
RETURN count(*), sum(i) 
GROUP BY ()
'''   
Treats all rows as a single group.

ORDER BY

Statement Description
'''
MATCH (v@Actor WHERE v.birthDate > date("1990-01-15")) 
ORDER BY v.birthDate ASC 
RETURN v.name, v.birthDate 
LIMIT 10
'''   
Sorts in ascending order using ASC.
'''
MATCH (v@Actor WHERE v.birthDate > date("1990-01-15")) 
ORDER BY v.birthDate DESC 
RETURN v.name, v.birthDate 
LIMIT 10
'''   
Sorts in descending order using DESC.
'''
MATCH (v@Actor) 
ORDER BY v.birthDate DESC NULLS FIRST 
RETURN DISTINCT v.birthDate AS birthday 
LIMIT 10
'''   
Places null values first using NULLS FIRST. When using DESC, NULLS LAST is the default.
'''
MATCH (v@Actor WHERE v.birthDate >= date("1971-01-01")) 
ORDER BY v.birthDate ASC, v.id DESC 
RETURN v.name, v.birthDate, v.id 
LIMIT 10
'''   
Sorts by multiple columns. Results are sorted by the first sort key; if the values are equal, results are further sorted by the second sort key, and so on until all sort keys are applied.

LIMIT

Statement Description
MATCH (v:Person) LIMIT 3 RETURN v.id
Specifies the maximum number of rows to return. If the limit is greater than or equal to the total number of rows, all rows are returned. Otherwise, the number of returned rows does not exceed the limit.

OFFSET

Statement Description
MATCH (v@Actor WHERE v.birthDate > date("1990-01-15")) OFFSET 3 ORDER BY v.birthDate RETURN v.id
Skips a specified number of rows in the result. If the offset is greater than the total number of rows, an empty result is returned.

SAMPLE

Statement Description
'''
USE movie 
MATCH (v1{id: 18})<-[e SAMPLE RIGHT FIRST_FETCH 2 ]-(v2)
RETURN labels(v1) AS anchor_labels,
       v1.id AS anchor_business_id,
       type(e) AS edge_type,
       count(*) AS sampled_count
'''   
Samples the first 2 edges.
'''
USE movie
MATCH (v1{id: 18})<-[e SAMPLE RIGHT RANDOM 10% ]->(v2)
RETURN labels(v1) AS anchor_labels,
       v1.id AS anchor_business_id,
       type(e) AS edge_type,
       count(*) AS sampled_count
'''   
Randomly samples 10% of the edges.
'''
USE movie 
MATCH p = (v1@Genre{id: 18})<-[e SAMPLE RIGHT UNIQUE_NEIGHBOR 2]-{1,2}(v2)
RETURN length(p) AS hops,
       transform(nodes(p), n -> n.id) AS node_business_ids,
       transform(e, edge -> type(edge)) AS edge_types
'''   
Randomly samples 2 edges connecting unique neighbors.

Functions

Math Functions

Statement Description
RETURN abs(3) AS intAbs, abs(-3.3) AS floatAbs
The abs() function returns the absolute value of a number.
RETURN mod(7,3) AS m
The mod() function returns the remainder of a division operation.
RETURN floor(1.3)
The floor() function returns the largest integer or decimal (with a fractional part of 0) that is less than or equal to the given number.
RETURN ceil(1.3) AS a
RETURN ceiling(1.3) AS a
The ceil() or ceiling() function returns the smallest integer or decimal (with a fractional part of 0) that is greater than or equal to the given number.
RETURN round(4.5) AS a, round(4.55, 1) AS b, round(45, -1) AS c
The round() function rounds a number to the specified precision.
RETURN exp(1)
The exp() function returns e raised to the specified power.
RETURN sign(-0.34)
The sign() function takes a float or integer as input and returns a specific integer value based on the sign of the input.
RETURN pi()
The pi() function returns the mathematical constant pi.
RETURN sqrt(3)
The sqrt() function returns the square root of a number.
RETURN power(3,4)
The power() function returns the result of raising a number to a power.
RETURN isnan(cosh(28))
The isnan() function checks whether the given number is NaN, returning true if it is and false otherwise.
RETURN rand() AS r
The rand() function returns a random float in the range 0 (inclusive) to 1 (exclusive).
RETURN rand_geo(0.5) AS r
RETURN rand_geometric(0.5) AS r
rand_geo() is an alias of rand_geometric(). Both functions return the number of failed trials before the first success in a geometric distribution.
RETURN log(7,7)
The log() function returns the logarithm of a number to a specified base.
RETURN log10(10)
The log10() function returns the base-10 logarithm of a number.
RETURN ln(271801.0/99990)
The ln() function returns the natural logarithm (base e) of a number.
RETURN sin(radians(90)) AS a
The sin() function returns the sine of a number.
RETURN cos(0) AS a
The cos() function returns the cosine of a number.
RETURN tan(0.25 * radians(180)) AS a
The tan() function returns the tangent of a number.
RETURN cot(0.25 * radians(180)) AS a
The cot() function returns the cotangent of a number.
RETURN sinh(radians(180)) AS a
The sinh() function returns the hyperbolic sine of a number.
RETURN cosh(radians(180)) AS a
The cosh() function returns the hyperbolic cosine of a number.
RETURN tanh(1)
The tanh() function returns the hyperbolic tangent of a number.
RETURN asin(radians(180))
The asin() function returns the arcsine of a number.
RETURN acos(radians(0))
The acos() function returns the arccosine of a number.
RETURN atan(radians(180))
The atan() function returns the arctangent of a number.
RETURN haversin(radians(0))
The haversin() function returns the haversine of a number.

Aggregate Functions

Statement Description
'''
MATCH (v1)-[e:Watch]->(v2 {id:199}) 
RETURN avg(e.rate) AS rate, v2.name AS movie GROUP BY movie
'''    
The avg() function returns the average of a set of values.
'''
MATCH (v1)-[e:Watch]->(v2 {id:1})  
ORDER BY e.rate ASC  
RETURN collect(e.rate) AS rate_collect, v2.name AS movie GROUP BY movie
'''    
The collect() function aggregates a set of values into a list. The collect_list() function is equivalent to collect().
'''
MATCH (v1)-[e:Watch]->(v2 {id:199}) 
RETURN count(e.rate) AS rate_count, v2.name AS movie GROUP BY movie
'''    
The count() function returns the count of a set of values.
'''
MATCH (v1)-[e:Watch]->(v2 {id:199}) 
RETURN max(e.rate) AS rate_max, v2.name AS movie GROUP BY movie
'''    
The max() function returns the maximum value in a set of values.
'''
MATCH (v1)-[e:Watch]->(v2 {id:199}) 
RETURN min(e.rate) AS rate_min, v2.name AS movie GROUP BY movie
'''    
The min() function returns the minimum value in a set of values.
'''
MATCH (v1)-[e:Watch]->(v2 {id:199}) 
RETURN sum(e.rate) AS rate_sum, v2.name AS movie GROUP BY movie
'''    
The sum() function returns the sum of a set of values.
'''
MATCH (v1)-[e:Watch]->(v2 {id:199}) 
RETURN stddev_pop(e.rate) AS rate_stddev_pop, v2.name AS movie GROUP BY movie
'''    
The stddev_pop() function returns the population standard deviation of a set of values.
'''
MATCH (v1)-[e:Watch]->(v2 {id:199}) 
RETURN stddev_samp(e.rate) AS rate_stddev_samp, v2.name AS movie GROUP BY movie
'''    
The stddev_samp() function returns the sample standard deviation of a set of values.
'''
MATCH (v1)-[e:Watch]->(v2 {id:199}) 
RETURN percentile_cont(e.rate, 0.5) AS r_percentile_cont, v2.name AS movie GROUP BY movie
'''    
The percentile_cont() function takes a percentile between 0 and 1 and returns the interpolated value at the position corresponding to that percentile in a sorted set of values.
'''
MATCH (v1)-[e:Watch]->(v2 {id:199}) 
RETURN percentile_disc(e.rate, 0.5) AS r_percentile_disc, v2.name AS movie GROUP BY movie
'''    
The percentile_disc() function takes a percentile between 0 and 1 and returns the actual value closest to the specified percentile in a sorted set of values, rather than an interpolated value.
MATCH (v@Actor) RETURN any_value(v) AS rr GROUP BY ()
The any_value() function returns an arbitrary value from a set of values.

For more information about aggregate expressions, see Aggregate Expressions.

String Functions

Statement Description
RETURN substring("abcdef", 1, 2) AS substr
The substring() function returns a substring of a string.
RETURN fmt('hello %s %s', 'my', 'world') AS a
The fmt() function formats the specified values and inserts them into placeholders in a string.
RETURN left("abcdef", 3) AS substr
The left() function returns the leftmost characters of a string with the specified length.
RETURN right("abcdef", 3) AS substr
The right() function returns the rightmost characters of a string with the specified length.
RETURN upper("abCDef") AS a
The upper() function converts all characters in a string to uppercase.
RETURN lower("abCDef") AS a
The lower() function converts all characters in a string to lowercase.
RETURN trim('_' FROM "__abc__") AS a
The trim() function returns the string with the specified characters removed from the left, right, or both sides.
RETURN ltrim('aabbccdd', 'abc') AS a
The ltrim() function returns the string with the specified characters removed from the left.
RETURN rtrim('aabbccdd', 'cd') AS a
The rtrim() function returns the string with the specified characters removed from the right.
RETURN length('nebula graph') AS l
The length() function returns the number of characters in a string.
RETURN contains('nebula graph', 'nebula') AS c
The contains() function returns true if the specified substring is found in the string.
RETURN like("hello, world", "hello, wo%") AS v
RETURN "hello, world" LIKE "hello, wo%" AS v
The like() function returns true if the string matches the specified pattern.
RETURN regexp_like("hello\n, world", "HELLO.*", 'inx') AS v
The regexp_like() function returns true if the string matches the specified regular expression.
RETURN split("a,b,c", ",") AS result
The split() function splits a string into a list of substrings using the specified regular expression as the delimiter.
RETURN md5("Hello World") AS hash
The md5() function returns the MD5 hash of a string.
RETURN index_of("a数据库✅bcadabad书ad", "ad") AS res
The index_of() function returns the starting position of the first occurrence of the specified substring in the target string.
RETURN indexes_of("a数据库✅bcadabad书ad", "ad") AS res
The indexes_of() function returns a list of all starting positions of the specified substring in the target string.
RETURN to_literal(-12) AS a
The to_literal() function returns the string representation of the input value.

Temporal Functions

Statement Description
RETURN date('2022-01-02') AS `date`
The date() function parses a string into a date.
RETURN local_datetime("2012-03-04T05:06:07.0890", "%Y-%m-%dT%H:%M:%S") AS localdatetime
The local_datetime() function parses a string into a local datetime.
RETURN zoned_datetime("2012-03-04ZONE05:06:07.123 AT -02:00", "%Y-%m-%dZONE%H:%M:%S AT %Ez") AS zoneddatetime
The zoned_datetime() function parses a string into a zoned datetime and returns a datetime with the session time zone.
RETURN zoned_time("05:06:07.123 AT -02:00", "%H:%M:%S AT %Ez") AS zonedtime
The zoned_time() function parses a string into a zoned time and returns a time with the session time zone.
RETURN local_time("05:06:07.123", "%H:%M:%S") AS localtime
The local_time() function parses a string into a local time.
RETURN CURRENT_TIME AS now_time
CURRENT_TIME is a keyword-style zero-argument function that returns the current zoned time in the session time zone.
RETURN CURRENT_TIMESTAMP AS now_ts
CURRENT_TIMESTAMP is a keyword-style zero-argument function that returns the current zoned datetime in the session time zone.
RETURN from_epoch(1333670400000*1000) AS dt
The from_epoch() function converts a microsecond-level Unix timestamp to a zoned datetime.
RETURN to_epoch(zoned_datetime("2012-04-06T08:00:00.000+08")) AS epoch
The to_epoch() function converts a zoned datetime to a microsecond-level Unix timestamp.
RETURN duration({days:1, hours:2, minutes:3, seconds:4, milliseconds:5, microseconds:6}) AS a
The duration() function parses a map value into a duration and returns a string in the ISO 8601 format P[nY][nM][nD]T[nH][nM][fS].
RETURN duration_between(local_datetime("2024-05-31T06:07:08.0900"), local_datetime("2024-5-1T01:02:03.0400")) AS a
The duration_between() function calculates the duration between two time points and returns the duration as a string.

Operations Between Time Points and Durations

Statement Description
RETURN date("2024-05-30") + duration({years: 1000, months: 10}) AS a
Adds a duration to a date.
RETURN date("2022-04-30") - duration({years: 2, months: 2}) AS a
Subtracts a duration from a date.
RETURN local_datetime("2024-05-31T01:05:05.0500") - duration({hours: 3, minutes: 3, seconds: 3, microseconds: 30000}) AS a
Subtracts a duration (less than one day) from a local datetime.
RETURN local_datetime("2021-02-28T03:03:03.0000") - duration({days: 365}) AS a
Subtracts a duration (greater than one day) from a local datetime.

List Functions

Statement Description
'''
MATCH p=(m@Movie)<-[e:Watch]-(n@`User`)
LET a = nodes(p)  
RETURN length(a) AS len LIMIT 3
'''   
The length() function returns the number of elements in a list.
RETURN cardinality([2,2,3]) AS a
The cardinality() function returns the number of elements in a list or record.
'''
MATCH p=(m@Movie)<-[e:Watch]-(n@`User`)
LET a = nodes(p)  
RETURN head(a) LIMIT 3
'''   
The head() function returns the first element of a list.
'''
MATCH p=(m@Movie)<-[e:Watch]-(n@`User`)
LET a = nodes(p)  
RETURN tail(a) LIMIT 3
'''   
The tail() function removes the first element from a list.
''' 
MATCH p=(m@Movie)<-[e:Watch]-(n@`User`)
LET a = nodes(p)  
RETURN back(a) LIMIT 3
'''   
The back() function returns the last element of a list.
RETURN range(-3,2) AS l
The range() function returns a list of integers from the start value to the end value, where the difference between any two consecutive values, called the step, is a constant.
'''
LET input = range(1,6) 
RETURN list_slice(input, 0, 3, 2) AS a
'''   
The list_slice() function returns a slice of a list from the start value to the end value.
RETURN trim([1,2,3,4], 2) AS a
The trim() function returns the list after removing the specified number of elements from the end.
RETURN zip([1,2,3],[4,5,6]) AS res
The zip() function pairs the elements at corresponding positions in two lists into sub-lists and then combines these sub-lists into a new list.
RETURN list_distinct([1,2,3,2,1,3,1,2,null]) AS res
The list_distinct() function removes duplicate values from the input list and returns a new list.
RETURN list_except([1,2,3,4,5],[3,4,4,4,4,4,null]) AS res
The list_except() function returns a list of elements that exist in list x but not in list y, with duplicates removed from the result.
RETURN list_intersect([null,1,2,3],[2,3,null,4]) AS res
The list_intersect() function returns a list of elements that are the intersection of list x and list y, with duplicates removed from the result.
RETURN list_join([1,null,3], ",") AS res
The list_join() function joins the elements of the input list using the specified delimiter, with an optional string to replace NULL values in the list.
RETURN list_max([-5,-3,-1,0,1,3,5]) AS res
The list_max() function returns the maximum value in the input list. If the list contains NULL values, it returns NULL.
RETURN list_min([-5,-3,-1,0,1,3,5]) AS res
The list_min() function returns the minimum value in the input list. If the list contains NULL values, it returns NULL.
RETURN list_union([1,2,3],[3,4,5]) AS res
The list_union() function returns a list of elements that are the union of list x and list y, with duplicates removed from the result.
RETURN list_sort([3,1,null,2,null]) AS res
The list_sort() function returns the list sorted in ascending order.
RETURN list_sum([1,2,3,4,5]) AS res
The list_sum() function returns the sum of all non-NULL elements in the list. If there are no non-NULL elements in the list, it returns 0.0.
RETURN remove_nulls([1,2,null,3,null,4]) AS res
The remove_nulls() function removes all NULL values from the input list.

Table Functions

Statement Description
'''
TABLE result_table TYPED TABLE {i INT, j INT}
FOR i IN range(1, 100)
FOR j IN range(1, 100)
EXPORT i, j INTO result_table
FOR t IN table_split(result_table)
RETURN sum(size(t))
'''   
Splits a table and counts the total number of rows.
'''
TABLE result_table TYPED TABLE {i INT, j INT}
FOR i IN range(1, 5)
FOR j IN range(1, 5)
EXPORT i, j INTO result_table
FOR t IN table_split(result_table, cast(10 as UINT))
RETURN size(t)
'''   
Splits a table by the specified size.
'''
TABLE result_table TYPED TABLE {i INT, j INT}
FOR i IN range(1, 3)
FOR j IN range(1, 3)
EXPORT i, j INTO result_table
FOR t IN table_split(result_table)
FOR r IN t
RETURN r.i as i, r.j as j
'''   
Iterates over rows in the sub-tables.

Set Functions

Statement Description
RETURN set_append(SET{1, 2, 3}, 4)
The set_append() function appends a new element to an existing set.
RETURN set_union(SET{1, 2, 3}, SET{3, 4, 5})
The set_union() function returns the union of two sets.
RETURN set_intersect(SET{1, 2, 3}, SET{2, 3, 4})
The set_intersect() function returns the intersection of two sets.
RETURN set_except(SET{1, 2, 3}, SET{2, 3, 4})
The set_except() function returns the difference of two sets.
RETURN set_sum(SET{1.0M, 2M})
The set_sum() function returns the sum of numeric elements in a set.
RETURN set_max(SET{1, 2, 3.0M})
The set_max() function returns the maximum value in a set.
RETURN set_min(SET{1, 2, 3.0M})
The set_min() function returns the minimum value in a set.
RETURN set_filter(SET{1, 2, 3, null}, x -> x IS NOT NULL)
The set_filter() function returns a new set containing elements that satisfy the predicate condition.
RETURN set_remove(SET{1, 2, 3}, 1)
The set_remove() function removes the specified element from a set.
RETURN remove_nulls(SET{1, null, 2})
The remove_nulls() function removes NULL values from a set.

Map Functions

Statement Description
RETURN map_append(MAP{1:"a"}, 2, "b")
The map_append() function appends a new key-value pair to an existing map.
RETURN map_replace(MAP{1:"old", 2:"b"}, 1, "new")
The map_replace() function replaces the value of the specified key in a map.
RETURN element_at(MAP{1:"a", 2:"b"}, 1)
The element_at() function returns the value of the specified key in a map.
RETURN map_keys(MAP{1:"a", 2:"b"})
The map_keys() function returns all keys in a map.
RETURN map_values(MAP{1:"a", 2:"b"})
The map_values() function returns all values in a map.
RETURN map_union(MAP{1:"a"}, MAP{2:"b"})
The map_union() function returns the union of two maps.
RETURN map_intersect(MAP{1:"a", 2:"b"}, MAP{1:"a", 3:"c"})
The map_intersect() function returns the intersection of two maps.
RETURN map_except(MAP{1:"a", 2:"b"}, MAP{2:"b"})
The map_except() function returns the difference of two maps.
RETURN map_filter(MAP{1:"a", 2:null, 3:"c"}, (k, v) -> v IS NOT NULL)
The map_filter() function returns a new map containing key-value pairs that satisfy the predicate condition.
RETURN map_remove(MAP{1:"a", 2:"b"}, 1)
The map_remove() function removes the key-value pair with the specified key from a map.
RETURN remove_nulls(MAP{1:"a", 2:"b", null:null})
The remove_nulls() function removes key-value pairs where both the key and value are NULL from a map.

Graph Functions

Statement Description
MATCH (v@Actor) RETURN element_id(v) LIMIT 5
The element_id() function returns the unique identifier of a node in the graph.
MATCH ()-[e]->() RETURN multiedge_id(e) AS e LIMIT 5
The multiedge_id() function returns a unique identifier for distinguishing a specific parallel edge based on its multi-edge key. If there are no parallel edges, it returns 0.
'''
MATCH (v1)-[e:Watch]->(v2 {id:1}) 
ORDER BY e.rate ASC 
RETURN left_node_id(collect(e)) AS src_id
'''   
The left_node_id() function returns the unique identifier of the left node of the specified edge in a given path.
'''
MATCH (v1)-[e:Watch]->(v2 {id:1}) 
ORDER BY e.rate ASC 
RETURN right_node_id(collect(e)) AS src_id
'''   
The right_node_id() function returns the unique identifier of the right node of the specified edge in a given path.
MATCH p=(m@Movie)<-[e:Watch]-(n@`User`) RETURN nodes(p) LIMIT 5
The nodes() function returns all nodes in a path as a list.
MATCH p=(m@Movie)<-[e:Watch]-(n@`User`) RETURN edges(p) AS p LIMIT 5
MATCH p=(m@Movie)<-[e:Watch]-(n@`User`) RETURN relationships(p) AS p LIMIT 5
The edges() or relationships() function returns all edges in a path as a list.
'''
MATCH p=(v@Genre)-[e2]-(m@Movie)-[e1]-(n@`User`) 
RETURN length(p) 
LIMIT 2
'''   
The length() function returns the length of a path.
MATCH p=(a:Movie{name:"Unpromised Land"})-[e:WithGenre]->{1,2}(b:Genre) RETURN cardinality(p) AS a
The cardinality() function returns the number of elements in a path.
'''
MATCH (v)-[e]->(m) 
WHERE v.id = 133 
RETURN labels(m) AS m_labels, labels(e) AS e_labels
'''   
The labels() function returns all labels of a graph element.
'''
MATCH (v@Director)->(w@Movie), (n@Actor)->(m@Movie), (u@`User`)->(p@Movie) 
WHERE NOT all_different(w, m, p) 
RETURN element_id(w)=element_id(m) AS wm, 
element_id(w)=element_id(p) AS wp, 
element_id(m)=element_id(p) AS mp 
LIMIT 1
'''   
The all_different() function returns true if all graph elements in the list are distinct from each other. Otherwise, it returns false.
'''
MATCH (v@Director{id:488})->(w@Movie), (n@Actor{id:9640})->(m@Movie), (u@`User`)->(p@Movie) 
WHERE SAME(w, m, p) 
RETURN w.name AS movie_name, v.name AS director, n.name AS actor 
LIMIT 3
'''   
The same() function returns true if all graph elements in the list are the same. Otherwise, it returns false.
'''
MATCH ()-[e]->() 
RETURN DISTINCT type(e) AS edge_types
'''   
The type() function returns the name of the element type to which a graph element belongs.

Lambda Functions

Statement Description
'''
MATCH p=(m:Movie)<-[e:Watch]-(n@`User`)
RETURN transform(nodes(p), x -> x.id) AS a 
LIMIT 5
'''   
The transform() function takes a list and a lambda expression and returns a new list with the transformation applied.
RETURN filter(LIST[1, 2, 3], x -> x > 2) AS a
The filter() function takes a list and a lambda expression and returns a new list containing only the elements from the original list that satisfy the lambda expression.
RETURN reduce(range(1,3), 100, (state, item) -> state + item) AS a
The reduce() function applies a lambda expression to each element in a list for cumulative computation and returns a single value.

For more information about lambda expressions, see Lambda Expressions.

Vector Functions

Statement Description
RETURN euclidean(VECTOR<3,FLOAT>([1,2,3]), VECTOR<3,FLOAT>([4,5,6])) AS euclidean_distance
The euclidean() function returns the Euclidean distance between two vectors.
RETURN inner_product(VECTOR<3,FLOAT>([1,2,3]), VECTOR<3,FLOAT>([4,5,6])) AS ip
The inner_product() function returns the inner product of two vectors.
RETURN cosine(VECTOR<3,FLOAT>([1,2,3]), VECTOR<3,FLOAT>([4,5,6])) AS cos
The cosine() function returns the cosine similarity between two vectors.
LET x = VECTOR<3, FLOAT>([1.1, -2.2, 3.3]) RETURN abs(x) AS x
The abs() function returns a vector where each element is the absolute value of the corresponding element in the given vector.
LET x = VECTOR<3, FLOAT>([1.1, -2.2, 3.3]) RETURN abs2(x) AS x
The abs2() function returns a vector where each element is the square of the corresponding element in the given vector.
LET x = VECTOR<3, FLOAT>([1.21,4.84,10.89]) RETURN sqrt(x) AS x
The sqrt() function returns a vector where each element is the square root of the corresponding element in the given vector.
LET x = VECTOR<3, FLOAT>([64.0, 256.0, 16.0]) RETURN ln(x) AS x
The ln() function returns a vector where each element is the natural logarithm (base e) of the corresponding element in the given vector.
LET x = VECTOR<3, FLOAT>([64.0, 256.0, 16.0]) RETURN log10(x) AS x
The log10() function returns a vector where each element is the base-10 logarithm of the corresponding element in the given vector.
LET x = VECTOR<3, FLOAT>([1, 2, 3]) RETURN exp(x) AS x
The exp() function returns a vector where each element is e raised to the power of the corresponding element in the given vector.
LET x = VECTOR<3, FLOAT>([1, 2, 3]) RETURN normalize(x) AS x
The normalize() function returns a normalized vector, adjusting the vector length to 1 while preserving the original direction.
LET x = VECTOR<3, FLOAT>([10.1, 20.2, 30.3]) RETURN accum(x) AS z
The accum() function returns the sum of all elements in the given vector.
LET x = VECTOR<3, FLOAT>([1.1, 2.2, 3.3]) RETURN mean(x) AS z
The mean() function returns the average of all elements in the given vector.
LET x = VECTOR<3, FLOAT>([1.1, 2.2, 3.3]) RETURN prod(x) AS z
The prod() function returns the product of all elements in the given vector.
LET x = VECTOR<3, FLOAT>([1.1, 2.2, 3.3]) RETURN norm(x) AS z
The norm() function returns the Euclidean norm of the given vector.
LET x = VECTOR<3, FLOAT>([1.1, 2.2, 3.3]) RETURN squared_norm(x) AS z
The squared_norm() function returns the squared Euclidean norm of the given vector.

Vector Arithmetic Operations

Statement Description
LET x = VECTOR<3, FLOAT>([10.1, 20.2, 30.3]), y = VECTOR<3, FLOAT>([2.2, 3.3, 4.4]) RETURN x + y AS z
Addition between vectors.
LET x = VECTOR<3, FLOAT>([10.1, 20.2, 30.3]), y = VECTOR<3, FLOAT>([2.0, 3.0, 4.0]) RETURN x - y AS z
Subtraction between vectors.
LET x = VECTOR<3, FLOAT>([1.1, 2.2, 3.3]) RETURN x + 1 AS x
Addition of a vector and a number.
LET x = VECTOR<3, FLOAT>([10.1, 2.2, 3.3]) RETURN x - 1 AS x
Subtraction of a number from a vector.
LET x = VECTOR<3, FLOAT>([1.1, 2.2, 3.3]) RETURN x * 2 AS x
Multiplication of a vector and a number.
LET x = VECTOR<3, FLOAT>([1.1, 2.2, 3.3]) RETURN x / 2 AS x
Division of a vector by a number.

Geospatial Functions

Statement Description
RETURN ST_Point(37.7749, -12.4194) AS point1
The ST_Point() function returns a Point based on the given longitude and latitude.
RETURN ST_GeogFromText('POINT(37.7749 -12.4194)') AS point1
The ST_GeogFromText() / ST_GeogFromWKT() function returns the geospatial value corresponding to the given WKT string.
RETURN ST_ASText(ST_Point(37.7749, -12.4194)) AS string_point
The ST_ASText() function returns the WKT string corresponding to a geospatial value.
RETURN ST_Centroid(ST_GeogFromText('POINT(37.7749 -12.4194)')) AS centroid1
The ST_Centroid() function returns the centroid of a geospatial value, i.e., the geometric center of the shape.
RETURN ST_ISValid(ST_Point(37.7749, -124.4194)) AS isValidPoint
The ST_ISValid() function returns true if the given geospatial value is valid; otherwise, it returns false.
RETURN ST_Intersects(ST_GeogFromText('POINT(0 1)'), ST_GeogFromText('POLYGON((0 1, 1 2, 2 3, 0 1))')) AS v
The ST_Intersects() function returns true if the two given geospatial values intersect (share at least one common point); otherwise, it returns false.
RETURN ST_IntersectionPoints(ST_GeogFromText("LineString(0 1,1 0)"),ST_GeogFromText("LineString(0 0,1 1)")) AS v
The ST_IntersectionPoints() function returns a list of intersection points of the boundaries of two geospatial values.
RETURN ST_Covers(ST_GeogFromText('POLYGON((0 1, 1 2, 3 0, 0 1))'), ST_GeogFromText('POINT(1 1)')) AS v
Given two geospatial values g1 and g2, the ST_Covers(g1, g2) function returns true if g1 completely contains g2 (i.e., all points of g2 lie on the interior or boundary of g1); otherwise, it returns false.
RETURN ST_CoveredBy(ST_GeogFromText('POLYGON((0 1, 1 2, 3 0, 0 1))'), ST_GeogFromText('POINT(1 1)')) AS v
Given two geospatial values g1 and g2, the ST_CoveredBy(g1, g2) function returns true if g2 completely contains g1 (i.e., all points of g1 lie on the interior or boundary of g2); otherwise, it returns false.
RETURN ST_DWithin(ST_GeogFromText("Point(0 0)"),ST_GeogFromText("Point(10 10)"),20000000000) AS v
The ST_DWithin() function returns true if the distance between at least one point in geospatial value g1 and at least one point in g2 is less than or equal to the given distance threshold; otherwise, it returns false.
RETURN ST_Distance(ST_GeogFromText("Point(0 0)"),ST_GeogFromText("Point(10 10)")) AS distance
The ST_Distance() function returns the shortest distance (in meters) between two geospatial values.
RETURN S2_CellIdFromPoint(ST_GeogFromText("Point(1 1)")) AS v
The S2_CellIdFromPoint() function returns the S2 cell ID covering a Point.
RETURN S2_CoveringCellIds(ST_GeogFromText("POLYGON((0 1, 1 2, 2 3, 0 1))")) AS v
The S2_CoveringCellIds() function returns a list of S2 cell IDs covering a geospatial value.

Full-Text Index Functions

Statement Description
'''
USE movie 
MATCH (v@Movie) 
WHERE ftscore(v.name, 'Uncle') > 0 
RETURN v.name AS movie_name
'''   
The ftscore() function returns the relevance score between the STRING value stored in the indexed property and the given query string.

System Information Functions

Statement Description
RETURN typeof(1) AS a
The typeof() function returns the input value type and supports ordinary value types, graph element reference types, and table types.

Value Expressions

Aggregate Expressions

Statement Description
FOR i in LIST [1,2,3,3,4,4] RETURN count(DISTINCT i), sum(ALL i) GROUP BY ()
Calculates the count of distinct values and the sum of all values.
MATCH ()-[e:Watch]->(v@Movie {id: 473}) RETURN collect(e.rate), avg(e.rate) GROUP BY ()
Returns all ratings and the average rating for a movie.

For more information about aggregate functions, see Aggregate Functions.

Variable Expressions

Statement Description
LET a = 1, b = 2 RETURN a + b AS c
Defines variables and returns them.
MATCH (a@`User`)-[e:Watch]->(b) RETURN a, e, b LIMIT 3
Returns node variables and edge variables.

Conditional Expressions

Statement Description
'''
FOR a IN LIST[1,2,3,4,5,6,7,8,9,10] RETURN CASE 
WHEN a<4 THEN false
WHEN a>5 THEN true 
END AS case_value
'''   
Returns different values based on conditions.
RETURN coalesce(NULL, 1, 2, 3, 4, 5) AS a
Returns the first non-NULL value using the coalesce function.

Constant Expressions

Statement Description
'''
RETURN 1 AS num1, 
3.4 AS num2, 
true AS bool1, 
"str literal" AS str1, 
DATE '2024-01-01' AS temporal1, 
DURATION ({years:1, months:2}) AS duration1, 
LIST [2,3,4] AS list1, 
{a:1, b:true, c:"str literal"} AS record1, 
NULL AS null1
'''   
Returns constant values of different types.

Construct Expression

Statement Description
RETURN LIST [1,2,3,4,5] AS l
Constructs a list.
RETURN RECORD {a:1, b:true, c:"str literal"} AS record1
Constructs a record.

Function Expressions

Statement Description
RETURN substring("abc", 1, 1) AS f2
Calls a function with multiple arguments.
RETURN abs(-32.4) AS f1, substring("abc", 1, 1) AS f2
Calls multiple functions.
RETURN date() AS currentDate
Calls a function with no arguments.

For the complete list of functions, see Functions.

Logical Expressions

Statement Description
RETURN true OR false AS a
Returns the result of a logical OR.
RETURN 1=2 AND 1=1 AS b
Returns the result of a logical AND.

Property Expressions

Statement Description
LET r = RECORD {a:1, b:true, c:"str literal"} RETURN r.c
Gets a field of a record.
MATCH (v@`User`)-[e:Watch]->() RETURN v.id, e.rate LIMIT 3
Gets the properties of a node and an edge.

Subquery Expressions

Statement Description
RETURN VALUE {FOR i IN LIST [1,2,3,4] RETURN i ORDER BY i LIMIT 1} AS sub
Returns a single value from a subquery.
RETURN EXISTS {USE movie MATCH (v@Actor) RETURN v} AS sub
Returns a boolean value from a subquery.

Type Cast Expressions

Statement Description
RETURN CAST (DATE "2012-03-04" AS STRING) AS a
Converts a temporal value to a string.
RETURN CAST (NULL AS INT16) AS a
Converts a null value to an integer of type INT16.
RETURN CAST ([1.4, 1.5] AS LIST<INT8>) AS a
Converts decimals in a list to integers of type INT8.
RETURN CAST ({p: LIST [1.4, 1.5]} AS RECORD {p LIST<INT32>}) AS a
Converts a record of decimals to a record of integers of type INT32.

Lambda Expressions

Statement Description
RETURN transform(LIST[1, 2, 3], x -> 2 * x + 1) AS a
Applies the transform() lambda function to a list.
RETURN filter(LIST[1, 2, 3, 4, 5], x -> x % 2 = 0) AS a
Applies the filter() lambda function to a list.
RETURN reduce(LIST[1, 2, 3, 4, 5], 0, (acc, x) -> acc + x) AS a
Applies the reduce() lambda function to a list.

For more information about lambda functions, see Lambda Functions.

Predicates

Comparison Predicates

Statement Description
LET l1= 'w55', l2='e34' RETURN l1 > l2 AS a
Compares strings. String comparison is based on the UCA algorithm.
RETURN (2>1) > (1>2) AS a, (2>1) <= (3>2) AS b
Compares boolean values. Boolean comparison is based on the rule that true is greater than false.
'''
RETURN null > (1>2) AS a,
       null >= 1 AS b,
       null < "String" AS c,
       null = LIST[1,2,3] AS d,
       null < local_datetime("2012-03-04T05:06:07.0890") AS e,
       null <> RECORD{} AS f
'''   
Compares null values. Any comparison with a null value returns null.
LET l1= LIST[1,2,3], l2=LIST[1,2,3.5] RETURN l1 = l2 AS a
Compares two lists. The comparison returns true if the two lists have the same elements in the same order; otherwise, it returns false.
LET t1=local_datetime("2012-03-04T05:06:07.0890"), t2=local_datetime("2012-03-02T05:06:07.0") RETURN t1 > t2 AS a
Compares time point values. Comparison of time point values is based on chronological order.
LET d1=duration({years:1, months:2}), d2=duration({years:1, months:3}) RETURN d1 < d2 AS a
Compares duration values. Comparison of duration values is based on duration length.
LET r1 = {a:1, b:true, c:"str"}, r2 = {a:1, c:"str", b:true} RETURN r1 = r2 AS a
Compares the field names and values of two records. The comparison returns true if the two records have the same fields and the same field values; otherwise, it returns false.
'''
MATCH (v1@Director)->(m1), (v2@Director)->(m2) 
WHERE m1.name = "Saw III" AND m2.name = "Saw IV" 
RETURN v1 = v2 AS a
'''   
Compares two graph elements for equality. The comparison returns true if the two graph elements are the same; otherwise, it returns false.
'''
MATCH p1 = (m1@Movie)<-(u1@`User`),
      p2 = (m2@Movie)<-(u2@`User`)
WHERE u1.id = u2.id 
RETURN p1 = p2 AS a, m1.name, m2.name 
LIMIT 5
'''   
Compares two paths for equality. The comparison returns true if the two paths are the same; otherwise, it returns false.

EXISTS Predicate

Statement Description
RETURN EXISTS { (v WHERE v.id= 123 ) } AS a
Checks whether a node pattern exists.
RETURN EXISTS ( ()-[e]->() WHERE e.id= 13423 ) AS b
Checks whether an edge pattern exists.
RETURN EXISTS { MATCH (a@`User`)-[e:Watch]->(b) WHERE a.id = 123 RETURN e } AS c
Checks whether a subgraph match is successful.

NULL Predicate

Statement Description
LET a= null>10 RETURN a IS NULL AS a_is_null
Checks whether a value is null.

Label Predicates

Statement Description
'''
MATCH (v)-[e]->() 
WHERE v IS LABELED Person 
RETURN DISTINCT v.name AS name 
LIMIT 5
'''   
Uses IS LABELED to check whether a graph element has a specific label.
'''
MATCH (v)-[e]->() 
WHERE e:Act 
RETURN DISTINCT e AS `edge` 
LIMIT 5
'''   
Uses the colon : to check whether a graph element has a specific label.
'''
MATCH (v)-[e]->() 
WHERE v IS NOT LABELED Person 
RETURN DISTINCT v.name 
LIMIT 5
'''   
Uses IS NOT LABELED to check whether a graph element does not have a specific label.

ALL_DIFFERENT Predicate

Statement Description
'''
MATCH (v@Director)->(w@Movie), (n@Actor)->(m@Movie), (u@`User`)->(p@Movie) 
WHERE NOT ALL_DIFFERENT(w, m, p) 
RETURN element_id(w)=element_id(m) AS wm, element_id(w)=element_id(p) AS wp, element_id(m)=element_id(p) AS mp 
LIMIT 1
'''   
Checks whether all graph elements in a list are pairwise distinct.

SAME Predicate

Statement Description
'''
MATCH (v@Director{id:488})->(w@Movie), (n@Actor{id:9640})->(m@Movie), (u@`User`)->(p@Movie) 
WHERE SAME(w, m, p) 
RETURN w.name AS movie_name, v.name AS director, n.name AS actor 
LIMIT 3
'''   
Checks whether all graph elements in a list are the same.

Performance Tuning

Statement Description
'''
EXPLAIN format = "default" 
MATCH (a:Person)-[e]->(b@Movie) 
LIMIT 1 RETURN b
'''   
Specifies the option format = "default" to view the optimized execution plan.
'''
EXPLAIN raw 
MATCH (a:Person)-[e]->(b@Movie) 
LIMIT 1 RETURN b
'''   
Specifies raw to view the unoptimized logical plan.
'''
EXPLAIN format = "verbose" 
MATCH (a:Person)-[e]->(b@Movie) 
LIMIT 1 RETURN b
'''   
Specifies the option format = "verbose" to view the detailed optimized execution plan.
'''
EXPLAIN raw format = "verbose" 
MATCH (a:Person)-[e]->(b@Movie) 
LIMIT 1 RETURN b
'''   
Specifies raw and format = "verbose" to view the detailed unoptimized logical plan.
'''
PROFILE format="default" 
MATCH (a:Person)-[e]->(b@Movie) 
LIMIT 1 RETURN b
'''   
Executes the query and specifies the option format = "default" to view the optimized execution plan.
'''
PROFILE format= "verbose" 
MATCH (a:Person)-[e]->(b@Movie) 
LIMIT 1 RETURN b
'''   
Executes the query and specifies the option format = "verbose" to view the detailed optimized execution plan.

Database Administration

SHOW

Command Description
SHOW ALL ROLES
Shows all roles in the current service group.
SHOW ALL INDEXES
Shows information about all indexes in the schema of the current session.
SHOW ALL WARNINGS
Shows all warnings generated by executing GQL statements in the current service group.
SHOW CONFIGS
Shows all runtime configuration items of the Graph service in the current session.
SHOW CONFIGS "192.168.8.129:9779"
Shows all runtime configuration items of the specified Storage service in the current session.
SHOW CONFIG session_idle_timeout_secs
Shows the specified runtime configuration item of the connected Graph service in the current session.
SHOW CONFIG "192.168.8.129:9779" audit_log_enabled
Shows the specified runtime configuration item of the specified Storage service.
SHOW CREATE GRAPH movie
Shows the statement used to create a specific graph.
SHOW CREATE GRAPH TYPE movie_type
Shows the statement used to create a specific graph type.
SHOW CREATE PROCEDURE test_proc
Shows the statement used to create a specific procedure.
SHOW CURRENT_SCHEMA
Shows the home schema of the current session.
SHOW CURRENT_SESSION
Shows the session created by the current user.
SHOW CURRENT_SESSION TIME FORMATS
Shows the date and time formats in the current session.
SHOW CURRENT_GRAPH
Shows information about the graph or temporary graph in the current session.
SHOW CURRENT_USER
Shows information about the logged-in user of the current session.
SHOW GLOBAL CONFIGS
Returns the configuration items set for all Graph services in the service group using GLOBAL SET or GLOBAL RESET.
SHOW GLOBAL CONFIGS STORAGE
Returns the configuration items set for all Storage services in the service group using GLOBAL SET or GLOBAL RESET.
SHOW FUNCTIONS
Shows all functions in the current catalog.
SHOW FUNCTION `mod`
Shows only the functions in the current catalog that match the specified function name.
SHOW GRAPHS
Shows all graphs in the current catalog.
SHOW GRAPH TYPES
Shows all graph types in the current catalog.
Use movie SHOW INDEXES
Shows the indexes created in the specified graph in the current catalog.
SHOW JOBS
Shows all running jobs in the current service group.
SHOW JOB 10
Shows a specific job in the current service group.
SHOW LEADERS
Shows information about the leader replicas on all Storage services in the current service group.
SHOW OBJECTS
Shows information about the resource objects owned by the current user.
SHOW OBJECTS FOR USER user1
Shows information about the resource objects owned by a specific user.
SHOW PARAMETERS
Shows all user-defined parameters in the current session.
SHOW PARTITIONS
Shows all partitions on the Storage services in the current service group.
SHOW PEERS
Shows detailed information about the replicas of all partitions on the Storage services in the current service group.
SHOW PEERS LEADER
Shows detailed information about all leader replicas on the Storage services in the current service group.
SHOW PLUGINS
Shows all plugins loaded in the current catalog.
SHOW PLUGIN log_rotate
Shows information about a specific plugin loaded in the current catalog.
SHOW PRIVILEGES FOR USER user1
Shows the privileges granted to a specific user.
SHOW PRIVILEGES FOR ROLE role1
Shows the privileges contained in a specific role.
SHOW PROCEDURES
Shows all named procedures in the current catalog.
SHOW PROCEDURE show_queries
Shows information about a specific named procedure in the current catalog.
SHOW QUERIES
Shows all running queries on the Graph services in the current service group.
SHOW ROLES
Shows the roles granted to the current user.
SHOW ROLES FOR USER user1
Shows the roles granted to a specific user.
SHOW SCHEMAS
Shows all schemas in the current catalog.
SHOW SERVICES
Shows all services in the current service group.
SHOW SERVICE CONFIGS
Shows the configuration items set for the currently connected Graph service.
SHOW SERVICE CONFIGS "192.168.8.129:9779"
Shows the configuration items set for the specified Storage service.
SHOW SERVICE GROUP
Shows information about the service group to which the currently connected Graph service belongs.
SHOW SERVICES META
Shows information about the Meta services in the current service group.
SHOW SESSIONS
Shows all active sessions on the Graph services in the current service group.
SHOW SESSION CONFIGS
Shows all configuration items set for the currently connected session using SESSION SET or SESSION RESET.
USE movie SHOW STATS
Shows the statistics of the specified graph.
USE movie SHOW TTLS
Shows the TTL settings of a specific graph.
SHOW VERSION
Shows the version information of the currently installed NebulaGraph Database Developer Edition.
SHOW VERSION VERBOSE
Shows the detailed version information of the currently installed NebulaGraph Database Developer Edition.
SHOW USERS
Shows all users invited to join the current service group.
SHOW WARNINGS
Shows the warnings generated by the last GQL statement in the current session.

DESCRIBE

Command Description
DESCRIBE GRAPH movie
Views graph information.
DESCRIBE GRAPH TYPE movie_type
Views graph type information.
DESCRIBE NODE TYPE Actor OF movie_type
Views node type information.
DESCRIBE EDGE TYPE Watch OF movie_type
Views edge type information.

KILL

Command Description
KILL QUERY "20231128_06303700005z3tjb"
Terminates a query.
KILL SESSION 1228399980662537
Terminates a session.

CLEAR

Command Description
CLEAR WARNINGS
Clears specific warnings generated by executing GQL statements in the current service group.
CLEAR ALL WARNINGS
Clears all warnings generated by executing GQL statements in the current service group.

Sessions

Command Description
SESSION SET timezone = "America/New_York"
Sets a session configuration item.
SESSION SET VALUE $i_1 = 10, $i_2 = 20
Sets parameters for the current session.
SESSION UNSET timezone
Unsets the time zone setting in the current session.
SESSION RESET timezone
Resets a session configuration item.
SESSION RESET $i_1, $i_2
Deletes the specified session parameters.
SESSION CLOSE
Closes the current session.
SHOW CURRENT_SESSION
Shows the session created by the current user.
SHOW CURRENT_SESSION TIME FORMATS
Shows the date and time formats in the current session.
SHOW SESSIONS
Shows all active sessions on the Graph services in the current service group.