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

如何在Gremlin查询中结合project与tree步骤实现分类层级结构

如何从图数据库中获取嵌套子分类的树形结构数据

我希望从图数据库中获取分类数据,让子分类嵌套在children属性中。我知道可以通过project步骤实现该需求,但不清楚如何将其与tree步骤结合使用。

期望的输出结构

[
    {
        "name": "shoes",
        "children": [
            {
                "name": "nike",
                "children": [
                    {
                        "name": "jordan 1",
                        "children": []
                    },
                    {
                        "name": "air force 1",
                        "children": []
                    }
                ]
            },
            {
                "name": "adidas",
                "children": [
                    {
                        "name": "yeezy",
                        "children": []
                    },
                    {
                        "name": "stan smith",
                        "children": []
                    }
                ]
            }
        ]
    }
]

图数据库结构示意图

图数据库结构示意图

图数据库初始化代码

g
.addV('category')
.property('name', 'shoes')
.as('shoes')
.addE('has')
.to(
    addV('category')
    .property('name', 'nike')
    .as('nike')
    .addE('has')
    .to(
        addV('category')
        .property('name', 'air force 1')
    )
    .select('nike')
    .addE('has')
    .to(
        addV('category')
        .property('name', 'jordan 1')
    )
    .select('nike')
)
.select('shoes')
.addE('has')
.to(
    addV('category')
    .property('name', 'adidas')
    .as('adidas')
    .addE('has')
    .to(
        addV('category')
        .property('name', 'yeezy')
    )
    .select('adidas')
    .addE('has')
    .to(
        addV('category')
        .property('name', 'stan smith')
    )
    .select('adidas')
)

解决方案

方法1:结合tree步骤与递归转换

先通过tree()获取原生树形结构,再用Groovy递归将其转换为目标嵌套格式:

g.V().hasLabel('category').has('name', 'shoes')
  .repeat(out('has').simplePath())
  .emit()
  .tree()
  .map { tree ->
    def buildTree = { node ->
      [
        name: node.get().value('name'),
        children: node.get().children().collect(buildTree)
      ]
    }
    [buildTree(tree.root())]
  }

方法2:多层project直接构造(适合固定层级)

如果分类层级固定,可直接用多层project+fold生成嵌套结构:

g.V().hasLabel('category').has('name', 'shoes')
  .project('name', 'children')
    .by('name')
    .by(
      out('has').fold().map { childNodes ->
        childNodes.collect {
          it.project('name', 'children')
            .by('name')
            .by(
              out('has').fold().map { grandChildNodes ->
                grandChildNodes.collect {
                  it.project('name', 'children')
                    .by('name')
                    .by(constant([]))
                }
              }
            )
        }
      }
    )

内容的提问来源于stack exchange,提问作者ephraim lambarte

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 22:29:51