0

我正在使用 Cosmos DB - Graph 来存储数据并开发 API 来查询图形数据库并以以下格式返回查询结果。API 可以接受任何节点类型和 id 作为参数并遍历 in & out 边以返回嵌套的顶点和边。

{
    "nodes":[
        {"id":"1","name":"A"},
        {"id":"2","name":"B"},
        {"id":"3","name":"C1"},
        {"id":"4","name":"C2"},
        {"id":"5","name":"C3"},
        {"id":"6","name":"D1"},
        {"id":"7","name":"D2"},
        {"id":"8","name":"D3"}
    ],
    "edges":[
        {"source":"1","target":"2"},
        {"source":"2","target":"3"},
        {"source":"2","target":"4"},
        {"source":"2","target":"5"},
        {"source":"3","target":"6"},
        {"source":"4","target":"7"},
        {"source":"5","target":"8"}
    ]
}

示例图:

示例图

我是 gremlin 图形查询的新手,并且面临遍历图形的问题。我有几个样本可以进出边缘并寻找顶点查询。我计划执行 4 个查询来生成上述格式:

对于边缘

g.V().has('name', 'A').repeat(__.bothE().where(without('e')).store('e').otherV()).cap('e')
g.V().has('name', 'A').repeat(__.inE().where(without('e')).store('e').outV()).cap('e')

对于节点

g.V().has('name', 'A').repeat(out()).until(outE().count().is(0)).simplePath()

我尝试了几个示例查询,但无法全部输入和输出顶点。我正在寻找返回所有顶点的查询或任何更好的解决方案来减少查询以构建 JSON 格式的输出。

4

2 回答 2

0

这个单一查询为您提供所需的输出:

g.V().has("name","C1").emit().repeat(bothE("e").simplePath()
  .sideEffect(project("source","target")
    .by(outV().id())
    .by(inV().id()).store("edges"))
  .otherV())
  .valueMap(true, "name").store("nodes").cap("nodes","edges")
于 2019-12-05T10:07:22.413 回答
0

根据您的描述和其他答案下方的评论,我想这就是您需要的:

g.V().has("name","C1").
  aggregate("n").
  union(outE().emit().repeat(inV().aggregate("n").outE()),
        inE().emit().repeat(outV().aggregate("n").inE())).
  project("source","target").
    by(outV().id()).
    by(inV().id()).fold().
  project("nodes","edges").
    by(select("n").
         by(unfold().
            project("id","name").
              by(id).
              by("name").
            fold())).
    by()

此查询在您的示例图上运行的结果将是:

gremlin> g.V().has("name","C1").
......1>   aggregate("n").
......2>   union(outE().emit().repeat(inV().aggregate("n").outE()),
......3>         inE().emit().repeat(outV().aggregate("n").inE())).
......4>   project("source","target").
......5>     by(outV().id()).
......6>     by(inV().id()).fold().
......7>   project("nodes","edges").
......8>     by(select("n").
......9>          by(unfold().
.....10>             project("id","name").
.....11>               by(id).
.....12>               by("name").
.....13>             fold())).
.....14>     by().next()
==>nodes=[{id=3, name=C1}, {id=6, name=D1}, {id=2, name=B}, {id=1, name=A}]
==>edges=[{source=3, target=6}, {source=2, target=3}, {source=1, target=2}]
于 2019-12-08T20:40:23.067 回答