K 邻模板 khop().<path_template>
使用固定长度的路径模板来描述最短路径,将满足第一个 n()
的多个点作为起点,批量地进行 K 邻查询,注意其参数 limit()
所限制的是每个子查询中每个起点的邻居数量,而非每个子查询中所有起点的邻居数量。
K 邻模板查询比实现同等功能的路径模板查询效率更高。
语法:
- 语句别名:支持,结构为 NODE
- 支持前缀 OPTIONAL,子查询无结果时返回
null
- 起始点模板
n()
的过滤条件不能为空 - 多边模板的步数
[<>]
只能是确定值,即[N]
- 不支持任何形式的步间过滤,无论是使用系统别名
prev_n
、prev_e
还是使用自定义的参数别名
例如,下图所示的 3 步路径中,点、边的过滤条件各不相同,传统的 K 邻查询无法描述这样的最短路径,可使用 K 邻模板对路径进行描述:
khop()
.n({_id in ["C001","C002"]}).re({@has}).n({@acct})
.re({@use}).n({@phone})
.le({@use}).n({@acct}) as n
示例图集:(以下示例将在本图基础上运行)
在空图集中依次运行以下各行代码以创建该图数据:create().node_schema("country").node_schema("movie").node_schema("director").edge_schema("filmedIn").edge_schema("direct")
create().node_property(@*, "name")
insert().into(@country).nodes([{_id:"C001", _uuid:1, name:"France"}, {_id:"C002", _uuid:2, name:"USA"}])
insert().into(@movie).nodes([{_id:"M001", _uuid:3, name:"Léon"}, {_id:"M002", _uuid:4, name:"The Terminator"}, {_id:"M003", _uuid:5, name:"Avatar"}])
insert().into(@director).nodes([{_id:"D001", _uuid:6, name:"Luc Besson"}, {_id:"D002", _uuid:7, name:"James Cameron"}])
insert().into(@filmedIn).edges([{_uuid:1, _from_uuid:3, _to_uuid:1}, {_uuid:2, _from_uuid:4, _to_uuid:1}, {_uuid:3, _from_uuid:3, _to_uuid:2}, {_uuid:4, _from_uuid:4, _to_uuid:2}, {_uuid:5, _from_uuid:5, _to_uuid:2}])
insert().into(@direct).edges([{_uuid:6, _from_uuid:6, _to_uuid:3}, {_uuid:7, _from_uuid:7, _to_uuid:4}, {_uuid:8, _from_uuid:7, _to_uuid:5}])
批量 K 邻查询
示例:查找各国经过 2 步最短路径 国家-电影-导演 所达的邻居,返回国名和导演名的对应表格
khop()
.n({@country} as a).le({@filmedIn}).n({@movie})
.le({@direct}).n({@director}) as b
return table(a.name, b.name)
| a.name | b.name |
|--------|---------------|
| France | Luc Besson |
| France | James Cameron |
| USA | Luc Besson |
| USA | James Cameron |
limit()
示例:查找各国经过 2 步最短路径 国家-电影-导演 所达的邻居,每个国家 1 个邻居,返回国名和导演名的对应表格
khop()
.n({@country} as a).le({@filmedIn}).n({@movie})
.le({@direct}).n({@director}).limit(1) as b
return table(a.name, b.name)
| a.name | b.name |
|--------|------------|
| France | Luc Besson |
| USA | Luc Besson |
OPTIONAL
示例:查找各国经过 3 步最短路径 国家-电影-国家-电影 所达的邻居,返回国名和导演名的对应表格;无结果的子查询返回 null
find().nodes({@country}) as a
optional khop()
.n(a).le({@filmedIn}).n({@movie})
.re({@filmedIn}).n({@country})
.le({@filmedIn}).n({@movie}) as b
return table(a.name, b.name)
| a.name | b.name |
|--------|--------|
| France | Avatar |
| USA | null |
分析:如不使用前缀 OPTIONAL,则不会返回表格中的第二行。