WITH 可以对别名进行函数运算,并将结果传递给后面的语句。输入中有异源别名时,对异源别名按行进行笛卡尔乘积组合。
语法:WITH <expression>
as <alias>
, <expression>
as <alias>
, ...
参数:
- <expression>:别名的运算表达式
- <alias>:运算结果的别名,可省略
WITH 子句中对某别名去重时,会影响其同源别名。
例如,对 n2.color 的去重操作影响了其同源数据流 pnodes(path);异源别名 n1、list 做笛卡尔乘积时,同样影响 list 的同源别名 color:
find().nodes() as n1 limit 2
n(3).e()[2].n(as n2) as path
with pnodes(path) as list, dedup(n2.color) as color
with n1, list
return n1, list, color
示例图集:(以下示例将在本图基础上运行)
在空图集中依次运行以下各行代码以创建该图数据:create().node_schema("account").node_schema("movie").edge_schema("rate").edge_schema("wishlist")
create().node_property(@*, "name").node_property(@account, "age", int32).node_property(@movie, "year", int32).edge_property(@rate, "score", int32)
insert().into(@account).nodes([{_id:"S001", _uuid:1, name:"Pepe", age:24}, {_id:"S002", _uuid:2, name:"Lina", age:23}, {_id:"S003", _uuid:3, name:"Emma", age:26}])
insert().into(@movie).nodes([{_id:"M001", _uuid:4, name:"Léon", year:1994}, {_id:"M002", _uuid:5, name:"Avatar", year:2009}])
insert().into(@rate).edges([{_uuid:1, _from_uuid:1, _to_uuid:4, score:9}, {_uuid:2, _from_uuid:3, _to_uuid:5, score:8}])
insert().into(@wishlist).edges([{_uuid:3, _from_uuid:2, _to_uuid:4}, {_uuid:4, _from_uuid:3, _to_uuid:4}])
函数运算
示例:查找 age 最小的所有 @account 点,返回 name
find().nodes({@account}) as a
with min(a.age) as minAge
find().nodes({@account.age == minAge}) as b
return b.name
Lina
分析:用 age 升序排列并限制返回一条数据的方法,可能会得不到所有年龄最小的 @account 点。
笛卡尔积
示例:将 @account 点和 @movie 点配对组合,查找 1 步路径 账号-电影,没有路径的组合返回 null
find().nodes({@account}) as a
find().nodes({@movie}) as b
with a, b
optional n(a).e().n(b) as p
return p{*}
Pepe --@rate--> Léon
null --null-- null
Lina --@wishlist--> Léon
null --null-- null
Emma --@wishlist--> Léon
Emma --@rate--> Avatar