第15期 Gremlin Steps:
coalesce()、optional()、union()
本系列文章的Gremlin示例均在HugeGraph图数据库上执行,环境搭建可参考准备Gremlin执行环境,本文示例均以其中的“TinkerPop关系图”为初始数据。

分支操作说明
- coalesce: 可以接受任意数量的遍历器(traversal),按顺序执行,并返回第一个能产生输出的遍历器的结果;
- optional: 只能接受一个遍历器(traversal),如果该遍历器能产生一个结果,则返回该结果,否则返回调用- optionalStep的元素本身。当连续使用- .optional()时,如果在某一步返回了调用元素本身,则后续的- .optional()不会继续执行;
- union: 可以接受任意数量的遍历器(traversal),并能够将各个遍历器的输出合并到一起;
实例讲解
下面通过实例来深入理解每一个操作。
- Step - coalesce()- 示例1: - 1 
 2
 3
 4
 5- // 按优先级寻找到顶点“HugeGraph”的以下边和邻接点,找到一个就停止 
 // 1、“implements”出边和邻接点
 // 2、“supports”出边和邻接点
 // 3、“created”入边和邻接点
 g.V('3:HugeGraph').coalesce(outE('implements'), outE('supports'), inE('created')).inV().path().by('name').by(label) - HugeGraph这三类边都是存在的,按照优先级,返回了“implements”出边和邻接点。 - 示例2: - 1 
 2
 3
 4
 5- // 按优先级寻找到顶点“HugeGraph”的以下边和邻接点,找到一个就停止(调换了示例1中的1和2的顺序) 
 // 1、“supports”出边和邻接点
 // 2、“implements”出边和邻接点
 // 3、“created”入边和邻接点
 g.V('3:HugeGraph').coalesce(outE('supports'), outE('implements'), inE('created')).inV().path().by('name').by(label) - 这次由于“supports”放在了“implements”的前面,所以返回了“supports”出边和邻接点。 - 自己动手比较一下 - outE('supports'), outE('implements'), inE('created')在- .coalesce()中随意调换顺序的区别。
- Step - optional()- 示例1: - 1 
 2- // 查找顶点"linary"的“created”出顶点,如果没有就返回"linary"自己 
 g.V('linary').optional(out('created')) - 示例2: - 1 
 2- // 查找顶点"linary"的“knows”出顶点,如果没有就返回"linary"自己 
 g.V('linary').optional(out('knows')) - 示例3: - 1 
 2- // 查找每个“person”顶点的出“knows”顶点,如果存在,然后以出“knows”顶点为起点,继续寻找其出“created”顶点,最后打印路径 
 g.V().hasLabel('person').optional(out('knows').optional(out('created'))).path() - 结果中的后面四个顶点因为没有出“knows”顶点,所以在第一步返回了自身后就停止了。 
- Step - union()- 示例1: - 1 
 2- // 寻找顶点“linary”的出“created”顶点,邻接“knows”顶点,并将结果合并 
 g.V('linary').union(out('created'), both('knows')).path() - 示例2: - 1 
 2- // 寻找顶点“HugeGraph”的入“created”顶点(创作者),出“implements”和出“supports”顶点,并将结果合并 
 g.V('3:HugeGraph').union(__.in('created'), out('implements'), out('supports'), out('contains')).path() - 顶点“HugeGraph”没有“contains”边,所以只打印出了其作者(入“created”),它实现的框架(出“implements”)和支持的特性(出“supports”)。