深入学习Gremlin(15):合并

第15期 Gremlin Steps:

coalesce()optional()union()

本系列文章的Gremlin示例均在HugeGraph图数据库上执行,环境搭建可参考准备Gremlin执行环境,本文示例均以其中的“TinkerPop关系图”为初始数据。

tinkerpop关系图

上一期:深入学习Gremlin(14):分支

分支操作说明
  • coalesce: 可以接受任意数量的遍历器(traversal),按顺序执行,并返回第一个能产生输出的遍历器的结果;
  • optional: 只能接受一个遍历器(traversal),如果该遍历器能产生一个结果,则返回该结果,否则返回调用optionalStep的元素本身。当连续使用.optional()时,如果在某一步返回了调用元素本身,则后续的.optional()不会继续执行;
  • union: 可以接受任意数量的遍历器(traversal),并能够将各个遍历器的输出合并到一起;
实例讲解

下面通过实例来深入理解每一个操作。

  1. Step coalesce()

    示例1:

    // 按优先级寻找到顶点“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:

    // 按优先级寻找到顶点“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()中随意调换顺序的区别。

  2. Step optional()

    示例1:

    // 查找顶点"linary"的“created”出顶点,如果没有就返回"linary"自己
    g.V('linary').optional(out('created'))
    

    示例2:

    // 查找顶点"linary"的“knows”出顶点,如果没有就返回"linary"自己
    g.V('linary').optional(out('knows'))
    

    示例3:

    // 查找每个“person”顶点的出“knows”顶点,如果存在,然后以出“knows”顶点为起点,继续寻找其出“created”顶点,最后打印路径
    g.V().hasLabel('person').optional(out('knows').optional(out('created'))).path()
    

    结果中的后面四个顶点因为没有出“knows”顶点,所以在第一步返回了自身后就停止了。

  3. Step union()

    示例1:

    // 寻找顶点“linary”的出“created”顶点,邻接“knows”顶点,并将结果合并
    g.V('linary').union(out('created'), both('knows')).path()
    

    示例2:

    // 寻找顶点“HugeGraph”的入“created”顶点(创作者),出“implements”和出“supports”顶点,并将结果合并
    g.V('3:HugeGraph').union(__.in('created'), out('implements'), out('supports'), out('contains')).path()
    

    顶点“HugeGraph”没有“contains”边,所以只打印出了其作者(入“created”),它实现的框架(出“implements”)和支持的特性(出“supports”)。

下一期:深入学习Gremlin(16):结果聚集与展开

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值