首页 > 解决方案 > Gremlin 查询以计算没有特定边的顶点

问题描述

我在 AWS 中有一个 Neptune 数据库,其图表如下:

图形

所以有一个用户组织了一个聚会并创建了两个邀请。但是用户已经撤回了其中一个邀请。

我正在寻找一个查询来计算尚未撤回的邀请数量(在上述情况下为 1)。

我找到了一种获取邀请的方法(我正在使用Gremlin 包 Javascript):

const result = await g
        .V("user#123")
        .inE().hasLabel("createdBy")
        .otherV()
        .toList();

但我似乎找不到任何东西来过滤那些已撤回的邀请。我不认为我可以遍历那些不是withdrawnBy因为那仍然会返回 2 的边缘(因为我们有一个createdBy和一个withdrawnBy边缘)。

有人有任何指示吗?我找到了这个答案,它建议:

gremlin> g.V.filter{!it.bothE('knows').hasNext()}

我假设这是 Groovy,但我使用的是 Javascript(实际上是 Typescript)。我已经尝试过该.filter()功能,但这似乎会引发错误:

.filter(function(this: any) {
    return !this.bothE("isRevokedBy");
})

标签: graphgremlinamazon-neptune

解决方案


你可以这样做:

g.V("user#123").as('u').
  in('createdBy').
  not(where(out('withdrawnBy').as('u')))

示例:https ://gremlify.com/crjfj88qrtfd8

但我认为最好在createdBy边缘添加一个属性,表明它已被撤销,而不是在它们之间添加另一个边缘。

像这样:

g.V("user#123").
  inE('createdBy').not(has('withdrawn', true)).outV()

示例:https ://gremlify.com/csfdv6w7325mb

当您使用 JavaScript 包时,这是可以工作的代码:

const gremlin = require("gremlin");
const __ = gremlin.process.statics;
const traversal = gremlin.process.AnonymousTraversalSource.traversal;
const DriverRemoteConnection = gremlin.driver.DriverRemoteConnection;
const dc = new DriverRemoteConnection("ws://localhost:8182/gremlin");
const g = traversal().withRemote(dc);

const result = await g
    .V("user#123")
    .in_("createdBy")
    .where(__.not(__.out("withdrawnBy")))
    .toList()

推荐阅读