Search code examples
javagremlintinkerpop3

ForEach step on Gremlin


I have a neo4j query like:

        ...
        "WITH DISTINCT k " +
        // classic for each loop for the new rankings information
        "FOREACH (app in $apps | " +
        // upsert the app
        " MERGE (a:App{appId:app.appId}) " +
        ...
        // end of loop
        ") " +

I'm using gremlin-java. In here, I want to give $apps as custom parameter. I've just checked gremlin document but I couldn't find a foreach step. Is there a suggestion?

graph.foreach(apps: map)...

Solved with:

...constant($apps).unfold().as(app)...

Solution

  • As you noted you can use a constant step to inject a value into a query. However you can also use the inject step to insert a collection of values in a similar way. Here are a couple of simple examples - you can extend these patterns to include id, label and multiple property values as needed.

    gremlin> g.inject([[id:1],[id:2],[id:3],[id:4]]).
               unfold().as('a').
               addV('test').
                 property('SpecialId',select('a').select('id'))
    ==>v[61367]
    ==>v[61369]
    ==>v[61371]
    ==>v[61373]
    
    gremlin> g.V().hasLabel('test').valueMap(true)
    ==>[id:61367,label:test,SpecialId:[1]]
    ==>[id:61369,label:test,SpecialId:[2]]
    ==>[id:61371,label:test,SpecialId:[3]]
    ==>[id:61373,label:test,SpecialId:[4]]
    
    
    
    gremlin> g.inject(1,2,3,4).as('a').
               addV('test2').
                 property('SpecialId',select('a'))
    ==>v[61375]
    ==>v[61377]
    ==>v[61379]
    ==>v[61381]
    
    gremlin> g.V().hasLabel('test2').valueMap(true)
    ==>[id:61375,label:test2,SpecialId:[1]]
    ==>[id:61377,label:test2,SpecialId:[2]]
    ==>[id:61379,label:test2,SpecialId:[3]]
    ==>[id:61381,label:test2,SpecialId:[4]]
    gremlin>
    

    The first query injects a list of maps. The second a simple list. This is a bit like the UNWIND pattern you may be used to in Cypher and it works in a similar way.