我正在使用gremlin Python来查询Neptune DB。给定一个顶点,我需要返回所有的向外边缘,包括它们的'from'和'to'id、label和其他属性。
下面的查询
query_result = g.V().has('name', 'marco').outE().inV().path().toList()
我的理想格式是 [{from: x, to: y, label: foo, property1: bar},...] 。
非常感谢任何帮助。
你可以用 elementMap
步。
g.V().has('name', 'marko').outE().inV().
path().
by(elementMap())
编辑:
如果 elementMap
不支持,您可以分别使用 by
在那里,你可以创建任何你想要的数据格式与 project
g.V().has('name', 'marko').outE().inV().
path().
by(valueMap(true)).by(union(
project('from', 'to').
by(outV().id()).
by(inV().id()),
valueMap(true)
).unfold().
group().by(keys).
by(select(values).unfold()))
你只要把结果投影出来,几乎可以得到你需要的结果。我将在结尾处添加一个例子来说明如何使其更加扁平化。你应该能够以任何你需要的方式调整这个查询,添加更多的 valueMap
步骤等。这不会产生一个单一的列表,而是将每个边缘与其属性、标签和ID进行分组。
请注意,我使用了 valueMap(true)
已被废弃,新的形式是...。valueMap().with(WithOptions.tokens)
. 目前这两种方法仍然有效。这种方法的好处是,不需要对 path
是需要的,一般来说,查询引擎在内存使用等方面更有效率。
gremlin> graph = TinkerFactory.createModern()
==>tinkergraph[vertices:6 edges:6]
gremlin> g = graph.traversal()
==>graphtraversalsource[tinkergraph[vertices:6 edges:6], standard]
gremlin> g.V().has('name','marko').
outE().
project('from','edge','to').
by(outV()).
by(valueMap(true)).
by(inV())
==>[from:v[1],edge:[id:9,label:created,weight:0.4],to:v[3]]
==>[from:v[1],edge:[id:7,label:knows,weight:0.5],to:v[2]]
==>[from:v[1],edge:[id:8,label:knows,weight:1.0],to:v[4]]
如果你想把这个结果扁平化成一个单一的列表,你可以在查询中多加一点。
gremlin> g.V().has('name','marko').
outE().
project('from','edge','to').
by(outV()).
by(valueMap(true)).
by(inV()).
union(select('edge').unfold(),
project('from').by(select('from')).unfold(),
project('to').by(select('to')).unfold()).fold()
[id=9,label=created,weight=0.4,from=v[1],to=v[3],id=7,label=knows,weight=0.5,from=v[1],to=v[2],id=8,label=knows,weight
=1.0,from=v[1],to=v[4]]
最后,如果你想得到一系列这样的列表,而不是一个大的列表,你可以把它包装成 union
踏进 local
范围。
gremlin> g.V().has('name','marko').
outE().
project('from','edge','to').
by(outV()).
by(valueMap(true)).
by(inV()).local(
union(select('edge').unfold(),
project('from').by(select('from')).unfold(),
project('to').by(select('to')).unfold()).fold())
==>[id=9,label=created,weight=0.4,from=v[1],to=v[3]]
==>[id=7,label=knows,weight=0.5,from=v[1],to=v[2]]
==>[id=8,label=knows,weight=1.0,from=v[1],to=v[4]]