Proper way to update Edges in Bulbs (neo4j or titan)

社会主义新天地 提交于 2019-12-06 04:18:18
espeed

You can add/update an edge's properties, but with graph databases, you cannot update the attributes that make it an edge, i.e. you cannot update its incoming and outgoing vertex IDs or label. Instead, you delete the edge and add a new one.

Here are the different ways of getting and edge and updating its properties..

You can get an edge by its ID:

>>> from bulbs.rexster import Graph
>>> g = Graph()
>>> james = g.vertices.create(name="James")
>>> julie = g.vertices.create(name="Julie")
>>> edge = g.edges.create(james, "knows", julie)
>>> edge2 = g.edges.get(edge.eid)       # get the edge again
>>> assert edge == edge2
>>> edge2.someprop = "somevalue"
>>> edge2.save()

You can look up an edge by its properties if it has any and they are indexed:

# will return an iterator or None edges (may return more than one)
>>> edges = g.edges.index.lookup(someprop="somevalue") 
>>> edge = edges.next()
>>> edge.someprop = "newvalue"
>>> edge.save()

# will return 1 or None edges (or an error if more than 1 edge found)
>>> edge = g.edges.index.get_unique(someprop="somevalue") 
>>> edge.someprop = "newvalue"
>>> edge.save()

You can also get an edge using Gremlin by traversing its vertices:

>>> from bulbs.rexster import Graph
>>> g = Graph()
>>> script = "g.V('name',name1).outE(label).as('e').inV.has('name',name2).back('e')"
>>> params = dict(name1="James", label="knows", name2="Julie")
>>> edges = g.gremlin.query(script, params)
>>> edge = edges.next()
>>> edge.someprop = "newvalue"
>>> edge.save()

See the Gremlin Backtrack Pattern...

But the most efficient way to update an edge when you don't know its ID is to update the edge via the Gremlin script that looks it up (this way you only have one round trip to the server, not two):

>>> from bulbs.rexster import Graph
>>> g = Graph()
>>> script = "g.V('name',name1).outE(label).as('e').inV.has('name',name2).back('e').sideEffect{it.someprop = someprop}"
>>> params = dict(name1="James", label="knows", name2="Julie", someprop="somevalue")
>>> edges = g.gremlin.query(script, params)
>>> edge = edges.next()
>>> edge.someprop
'somevalue'

See https://github.com/tinkerpop/gremlin/wiki/Updating-a-Graph

And for readability, rather than writing Gremlin one liners in the Python REPL, I would put my Gremlin scripts in a gremlin.groovy file, as shown here:

http://bulbflow.com/docs/api/bulbs/groovy/

Here is a real-life example of using Gremlin to get or create an edge:

https://github.com/espeed/lightbulb/blob/master/lightbulb/gremlin.groovy#L88

And a detailed explanation of the code is here:

Is there a equivalent to commit in bulbs framework for neo4j

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!