You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AWS AppSync调用Lambda用Gremlin创建顶点后无法创建Edge报错咨询

错误原因与修正方案

核心错误点

  • addE().from()/addE().to()的入参类型错误:这两个方法仅接受未执行的Gremlin遍历对象或者顶点实例作为参数,你代码中传入的是g.V().hasLabel('posts').next()的执行结果,next()方法执行后返回的是结构为{value: 结果内容, done: 布尔值}的普通对象,既不是遍历器也不是顶点实例,导致调用链无法识别from方法。
  • 逻辑冗余错误:你当前的边创建逻辑没有关联刚创建的新posts顶点,是随机匹配两个已有posts顶点创建边,不符合业务预期。
  • 多余远程调用:你分开执行顶点创建、边创建两次遍历请求,额外增加了网络开销,Gremlin支持单条遍历完成顶点+边的创建操作。

修正后代码

import { process as gprocess } from 'gremlin';
import Post from './Post'
const gremlin = require('gremlin')
const DriverRemoteConnection = gremlin.driver.DriverRemoteConnection
const Graph = gremlin.structure.Graph
const uri = process.env.WRITER
const { t, P } = gprocess;
const __ = gprocess.statics;

async function createPost(post: Post) {
    let dc: DriverRemoteConnection | null = null;
    try {
        dc = new DriverRemoteConnection(`wss://${uri}/gremlin`, {})
        const graph = new Graph()
        const g = graph.traversal().withRemote(dc)  

        // 单条遍历完成:创建顶点 + 同时创建边(示例为新顶点关联指定的目标posts顶点,可按需调整逻辑)
        // 如果你需要给两个指定顶点连边,直接把两个顶点的遍历写在from/to里即可,不需要先单独查顶点
        const result = await g.addV('posts')
            .property('title', post.title)
            .property('content', post.content)
            // 如果是要设置顶点的系统ID,要用t.id,property('id')是设置自定义属性
            .property(t.id, post.id)
            // 示例:给新创建的顶点和id为xxxx的目标posts顶点创建post_to_post边,可按需调整目标顶点的匹配条件
            .addE('post_to_post')
            .from(__.V(post.id)) // 这里传未执行的遍历即可,也可以直接写__.V().has('xxx', 'xxx')
            .to(__.V('目标顶点的id'))
            .next()

        return post;
    } finally {
        // 连接关闭放在finally块,避免异常时连接泄漏
        if (dc) await dc.close()
    }
}

export default createPost

额外注意事项

  • 如果你的边是要关联两个已经存在的顶点,不需要提前调用next()查询顶点,直接把顶点匹配的遍历语句传入from/to即可,示例如下:
    await g.addE('post_to_post')
      .from(g.V('顶点1的id'))
      .to(g.V('顶点2的id'))
      .next()
    
  • Gremlin的方法调用链在调用next()/toList()等终止方法前都只是未执行的遍历对象,可以任意拼接步骤,只有调用终止方法才会真正提交到服务端执行。

内容的提问来源于stack exchange,提问作者Hamza Ahmed Sheikh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 07:54:03