49172

Merging maps in Gremlin

<h3>Question</h3>

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

<ol><li>

Must include <em>all</em> properties of a vertex, without specifying individual fields in the query.

</li> <li>

Must flatten results at the same level on the object.

</li> </ol>

As separate queries, I can do:

<h3>1. valueMap query</h3> g.V(1) .valueMap().by(unfold()).fold()

Response:

<pre class="lang-json prettyprint-override">{ "property1": "value1", "property2": "value2" } <h3>2. project query</h3> g.V(1) .project("projectedProperty") .by(out("X").valueMap().by(unfold()).fold())

Response:

<pre class="lang-json prettyprint-override">{ "projectedProperty": "value", } <h3>Combined query</h3>

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:

<pre class="lang-json prettyprint-override">{ [ { "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:

<pre class="lang-json prettyprint-override">{ "property1": "value1", "property2": "value2", "projectedProperty": "value" }

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


<h3>Answer1:</h3>

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]

来源:https://stackoverflow.com/questions/60307292/merging-maps-in-gremlin

Recommend