Thirumal
Thirumal

Reputation: 9546

How to recreate a vertex with apache tinkerpop gremlin?

I need to replace the vertex T.id, unfortunately, it's not allowed in Apache Tinkerpop Gremlin. So I need to delete the vertex and create a new one with the same properties and incoming & outgoing edges.

Is there any easy way/shortcut to re-create?

Upvotes: 0

Views: 211

Answers (2)

Thirumal
Thirumal

Reputation: 9546

There is no transaction support in AWS Neptune, so I had to use the script. Here is the python function to generate a script to clone vertex and move edges.

#Clone Vertex -> Drop Edges -> Move Edges -> Drop old Vertex
def generate_recreate_vertex(old_id, new_id):
    clone_vertex_with_new_id = 'g.V(\'{}\').as(\'old_vertex\').addV().property(label, select(\'old_vertex\').label()).property(T.id, \'{}\').as(\'new_vertex\').select(\'old_vertex\').properties().as(\'old_vertex_properties\').select(\'new_vertex\').property(select(\'old_vertex_properties\').key(), select(\'old_vertex_properties\').value()).iterate();'.format(old_id, new_id)
    edges = g.V(old_id).bothE().elementMap().toList()
    edge_script = ""
    for edge in edges:
        edge_id = edge['id']
        outE = '.from(g.V(\'{}\'))'.format(new_id if edge['OUT']['id'] == old_id else edge['OUT']['id'])
        inE = '.to(g.V(\'{}\'))'.format(new_id if edge['IN']['id'] == old_id else edge['IN']['id'])
        edge_script += 'g.E(\'{}\').drop().iterate();'.format(edge_id)
        edge_script += 'g.addE(\'{}\'){}{}.property(T.id, \'{}\')'.format(edge['label'], inE, outE, edge_id)
        for k, v in edge.items():
            if k not in ['label', 'id', 'IN', 'OUT']:
                edge_script += '.property(\'{}\', \'{}\')'.format(k, v)
        edge_script += ".iterate();"
    #
    vertex_drop = 'g.V(\'{}\').drop()'.format(old_id)
    script = clone_vertex_with_new_id + edge_script + vertex_drop
    return script

https://github.com/M-Thirumal/gremlin-functions/blob/main/generate-recreate-vertex-script.py

Upvotes: 0

Kelvin Lawrence
Kelvin Lawrence

Reputation: 14371

One approach is to make a clone of the vertex you are going to delete first. This can be done in Gremlin.

Here is one way to clone the DFW vertex in the air routes data set. You can amend this code to also add your new ID value.

g.V().has('code','DFW').as('dfw').
      addV().property(label, select('dfw').label()).as('new').
      select('dfw').properties().as('dfwprops').
      select('new').property(select('dfwprops').key(),
                             select('dfwprops').value())

There is an example and discussion here http://www.kelvinlawrence.net/book/PracticalGremlin.html#dfwcopy

UPDATED

Adding a link to the recipe for moving edges.

https://tinkerpop.apache.org/docs/current/recipes/#edge-move

Upvotes: 1

Related Questions