Search code examples
gremlingremlin-serverazure-cosmosdb-gremlinapi

How to merge multiple objects into one, in gremlin query?


I have performed union in my query which gives me the following output

{
    key1 = value1,
    key2 = value2
},
{
    key3 = value3
}

I need output as follows,

{
    key1 = value1,
    key2 = value2,
    key3 = value3
}

Solution

  • You have to deconstruct and reconstruct the maps. This operation is described in some detail in Gremlin Recipes if you want to read more.

    The following code gets you to the position of your union():

    gremlin> x = [[key1:"value1",key2:"value2"],[key3:"value3"]]
    ==>[key1:value1,key2:value2]
    ==>[key3:value3]
    gremlin> g.inject(x).unfold()
    ==>[key1:value1,key2:value2]
    ==>[key3:value3]
    

    Then you just unfold() those maps to map entries (i.e. key/value pairs) and group() them back together:

    gremlin> g.inject(x).unfold().unfold().group().by(keys).by(values)
    ==>[key1:[value1],key2:[value2],key3:[value3]]
    gremlin> g.inject(x).unfold().unfold().group().by(keys).by(select(values))
    ==>[key1:value1,key2:value2,key3:value3]