Search code examples
gremlintinkerpop3

Gremlin: Add edges to multiple vertices


I have vertices [song1, song2, song3, user].

I want to add edges listened from user to the songs.

I have the following:

g.V().is(within(song1, song2, song3)).addE('listened').from(user)

However I'm getting the following error:

No signature of method: org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.DefaultGraphTraversal.from() is applicable for argument types: (org.janusgraph.graphdb.vertices.CacheVertex) values: [v[4344]] Possible solutions: sort(), drop(int), sum(), find(), grep(), sort(groovy.lang.Closure)

Of course, I can iterate through them one at a time instead but a single query would be nice:

user.addEdge('listened', song1)
user.addEdge('listened', song2)
user.addEdge('listened', song3)

Solution

  • The from() modulator accepts two things:

    1. a step label or
    2. a traversal

    A single vertex or a list of vertices can easily be turned into a traversal by wrapping it in V(). Also, note that g.V().is(within(...)) will most likely end up being a full scan over all vertices; it pretty much depends on the provider implementation, but you should prefer to use g.V(<list of vertices>) instead. Thus your traversal should look more like any of these:

    g.V().is(within(song1, song2, song3)).
      addE('listened').from(V(user)) // actually bad, as it's potentially a full scan
    
    g.V(song1, song2, song3).
      addE('listened').from(V(user))
    
    g.V(user).as('u').
      V(within(song1, song2, song3)).
      addE('listened').from('u')