Search code examples
javagremlintinkerpopamazon-neptune

Join query in gremlin, group results in a one to many relationship


I have to type of vertices Country and Airports, and each country has an edge to multiple airports with label "hasAirport"

I'm trying a join query which will return Countries grouped with the Airports they have.

g.V().hasLabel("Country").as("country").out('hasAirport').as("airport").select("country", "airport").by(__.unfold().valueMap(true).fold()).toList()

The if I have only one Country say United States with two airports in my graph, the result of the query is something like below.

[   {
    "country": [
      {
        "name": "United States",
        "code": "USA",      "label": "Country",
        "id": 1565,
      }
    ],
    "airport": [
      {
        "id": 1234,
        "label": "Airport",
        "name": "San Francisco International Airport",      "code": "SFO"
      }
    ]   },   {
    "country": [
      {
        "name": "United States",
        "code": "USA",      "label": "Country",
        "id": 1565,
      }
    ],
    "airport": [
      {
        "id": 2345,
        "label": "Airport",
        "name": "Austin Bergstrom International Airport",       "code": "AUS"
      }
    ]   }  ]

Is there a way to club multiple airports in a single array like below

[
  {
    "country": [
      {
        "name": "United States",
        "code": "USA",
        "label": "Country",
        "id": 1565,
      }
    ],
    "airport": [
      {
        "id": 1234,
        "label": "Airport",
        "name": "San Francisco International Airport",
        "code": "SFO"
      },
      {
        "id": 2345,
        "label": "Airport",
        "name": "Austin Bergstrom International Airport",
        "code": "AUS"
      }
    ]
  }
 ]

Solution

  • You need to use project:

    g.V().hasLabel("Country")
    .project("country","airport")
    .by(valueMap(true))
    .by(out('hasAirport').valueMap(true).fold())