我正在使用Cosmos DB-图形来存储数据,并正在开发API以查询图形数据库并以以下格式返回查询结果。 API可以接受任何节点类型和id作为参数,并遍历出入边缘以返回嵌套的顶点和边缘。
{
"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个查询以生成上述格式:
对于Edges
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格式构建输出。
答案 0 :(得分:0)
此单个查询为您提供所需的输出:
std::back_inserter(y)
答案 1 :(得分: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}]