Search code examples
gremlingraph-databasesgremlin-serveramazon-neptune

How to use multiple hashmaps in gremlin to generate dynamic properties when adding vertices


I want to create PARENT - HAS_CHILD -> CHILD nodes in my graph database using single gremlin traversal.

Problem is that PARENT vertex, HAS_CHILD edge and CHILD vertex have different properties and should come from different Hashmaps.

I am using java api for gremlin.

I have not found any way of doing it and would appreciate help on this.

Update:::

I was able to achieve using multiple maps like this:

Map<String, String> map1 = new HashMap<String, String>(); map1.put("a", "1"); map1.put("b", "2"); map1.put("c", "3");

Map<String, String> map2 = new HashMap<String, String>(); map2.put("aa", "11"); map2.put("bb", "22"); map2.put("cc", "33");

g.withSideEffect("map1", map1).withSideEffect("map2", map2) .addV(label).as("vertex1").sideEffect(__.select("map1").unfold().as("kv").select("vertex1").property(__.select("kv").by(Column.keys),
__.select("kv").by(Column.values))) .addV(label).as("vertex2").sideEffect(__.select("map2").unfold().as("kv").select("vertex2").property(__.select("kv").by(Column.keys),__.select("kv").by(Column.values))) .iterate();

Thanks for the help.


Solution

  • The answer to this problem is pretty similar to other questions on using a Map of properties to dynamically construct vertices and edges. That patterns are largely the same and derive from using unfold() to deconstruct a Map of properties to a stream of pairs and then calling property(k,v) for each. The approach is described in some detail in this blog post. While that post describes the loading of a single vertex, the ability to adapt that example to what you're looking for comes from understanding basic collection manipulation functions of Gremlin.

    gremlin> pair = [[name:'marko',age:29,country:'usa'],[name:'stephen',age:33,country:'usa']]
    ==>[name:marko,age:29,country:usa]
    ==>[name:stephen,age:33,country:usa]
    gremlin> g.withSideEffect('pair',pair).
    ......1>   addV('person').as('o').
    ......2>   sideEffect(select('pair').limit(local,1).
    ......3>              unfold().as('kvo').
    ......4>              select('o').
    ......5>              property(select('kvo').by(Column.keys), select('kvo').by(Column.values))).
    ......6>   addV('person').as('i').
    ......7>   sideEffect(select('pair').tail(local).
    ......8>              unfold().as('kvi').
    ......9>              select('i').
    .....10>              property(select('kvi').by(Column.keys), select('kvi').by(Column.values))).
    .....11>   addE('knows').
    .....12>     from('o').to('i').iterate()
    gremlin> g.V().elementMap()
    ==>[id:0,label:person,country:usa,name:marko,age:29]
    ==>[id:4,label:person,country:usa,name:stephen,age:33]
    gremlin> g.E()
    ==>e[8][0-knows->4]