Gremlin python return 具有所有属性的边

Gremlin python return edges with all properties

我正在使用 gremlin Python 查询 Neptune 数据库。给定一个顶点,我需要 return 所有外边及其 'from' 和 'to' id、标签和任何其他属性。

下面的查询

query_result = g.V().has('name', 'marco').outE().inV().path().toList()

给我 'from' 和 'to' 的形式,我可以解析成字典列表,边缘的值映射给了我其他值,但我需要它 returned 在一个列表中。我理想的格式是 [{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()))

示例:https://gremlify.com/ab

只需简单地投影结果,您几乎可以得到您需要的结果。我将在最后添加一个示例,说明如何进一步展平它。您应该能够以任何方式调整此查询,您需要添加更多 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]]