I'm working with gremlin and gremlinpython for the first time, and I'm hitting a wall when I try to create new vertexes and an edge between them. I've looked at some of the other resources online, but I'm kind of reaching my wits end. Here is what I have so far.

def merge_vertexes_and_edge(g, name1:str, name2:str, src: int, dest: int):
    g.V().has('name', name1).fold().coalesce(
        unfold(),
        addV('node').property('id', str(src)).property('name', name1)
    ).as_('v1').V().has('name', name2).fold().coalesce(
        unfold(),
        addV('node').property('id', str(dest)).property('name', name2)
    ).as_('v2').V('v1').out('knows').has('name', name2).fold().coalesce(
        unfold(),
        addE('knows').from_('v1').to('v2').property('name', f"{src}-{dest}")
    ).iterate()
    ```
1

There are 1 best solutions below

0
eathren On

I created two helper functions, that for now, do well enough.

# Helper function to create an edge between two vertices if it doesn't exist
def create_edge(g, src: int, dest: int):
    # Get the vertices by their ids
    v1 = g.V().has('id', src).next()
    v2 = g.V().has('id', dest).next()

    # Check if an edge between v1 and v2 already exists by name
    edge_exists = g.V(v1).out('knows').has('name', f"{src}-{dest}").hasNext()

    if not edge_exists:
        # Edge doesn't exist, so add it
        g.V(v1).as_('v1').V(v2).addE('knows').to('v1').property('name', f"{src}-{dest}").iterate()


# Helper function to create a vertex if it doesn't exist
def create_vertex(g, id: int, name: str):
    # Check if a vertex with the given name already exists
    vertex_exists = g.V().has('name', name).hasNext()
    
    if not vertex_exists:
        # Vertex doesn't exist, so add it
        g.addV('node').property('id', str(id)).property('name', name).iterate()