Merging maps in Gremlin
Asked Answered
D

1

7

I'm trying to write a single query that satisfies two requirements in the response object:

  1. Must include all properties of a vertex, without specifying individual fields in the query.

  2. Must flatten results at the same level on the object.

As separate queries, I can do:

1. valueMap query

g.V(1)
.valueMap().by(unfold()).fold()

Response:

{
  "property1": "value1",
  "property2": "value2"
}

2. project query

g.V(1)
.project("projectedProperty")
.by(out("X").valueMap().by(unfold()).fold())

Response:

{
  "projectedProperty": "value",
}

Combined query

I've attempted to use a union to combine these results:

g.V(1)
.union(
  valueMap().by(unfold()).fold(), // Query 1
  project("projectedField").by(out("X").valueMap().by(unfold()).fold()) // Query 2
).fold()

Response:

{
  [
    {
      "property1": "value1",
      "property2": "value2"
    },
    {
      "projectedProperty": "value"
    }
  ]
}

This union approach relies on me putting a fold at the end, which in turn doesn't merge/flatten the two maps properly. Expected response is:

{
  "property1": "value1",
  "property2": "value2",
  "projectedProperty": "value"
}

Is there a better way to accomplish this task of merging/flattening two maps in the response object?

Demulcent answered 19/2, 2020 at 18:48 Comment(0)
R
7

The typical pattern is to unfold() your maps to entries (keys/values) then group() them back together as one:

gremlin> g.V().has('person','name','marko').
......1>   union(project('count').by(outE().count()), elementMap()).
......2>   unfold().
......3>   group().by(keys).by(select(values))
==>[count:3,name:marko,label:person,id:1,age:29]
Reneta answered 19/2, 2020 at 19:30 Comment(2)
This worked, thank you. Specifically, I had to append unfold().group().by(keys).by(select(values)) after the union.Demulcent
this does not work when there are multiple results. i receive only the first resultPlacentation

© 2022 - 2024 — McMap. All rights reserved.