Home > Blockchain >  How to get a properly formatted Tree hierarchy Json using Gremlin query
How to get a properly formatted Tree hierarchy Json using Gremlin query

Time:05-21

I am trying to retrieve the Tree hierarchy structure from AWS Neptune DB. i am using the below query to retrieve the data in JSON format

g.V().hasLabel(labelid.toLowerCase()).has("name", "Val oswalt").repeat(__.inE().outV()).emit()
                    .tree().by(__.valueMap("name")).toList();

this returns me data in the below json format.

[
  {
    "{name=[Val oswalt]}": {
      "{}": {
        "{name=[Stan Polomoski]}": {
          "{}": {
            "{name=[MC Regan]}": {}
          }
        }
      }
    }
  }
]

Is it possible to return the data in a proper json format or a Flare json format something like below

{
  "name": "Val oswalt",
  "children": [
    {
      "name": "Stan Polomoski",
      "children": [
        {
          "name": "MC Regan"
        }
      ]
    }
  ]
}

CodePudding user response:

It's hard to use Gremlin to convert tree() results to anything more than the base structure it provides because post processing the returned Tree with Gremlin to recursively convert parent/child pairs to new key/value pairs is going to add a lot of unreadable code to your query.

It's a bit odd that your results are returning as what looks like String representations of the Map which you get by doing a valueMap('name'). Unless you are using Gremlin from a programming language that does not support Map values as keys, I'd expect you to get an actual Map object there that you could work with.

All that said, based on what you are targeting for an output, it looks like you could get closer to that form (without overly complicating your Gremlin) by doing something like:

g.V().hasLabel(labelid.toLowerCase()).
      has("name", "Val oswalt").
  repeat(__.in()).emit().
  tree().
    by("name")

which should yield something like:

{
  "Val oswalt": [
    {
      "Stan Polomoski": [
        {
          "MC Regan": []
        }
      ]
    }
  ]
}

While not quite the same output, it is definitely cleaner and implies the same structure. If you simply must have the structure you requested, I'd highly recommend you keep your Gremlin simple by utilizing the revised query I suggested and then post-process the result within your application to get that structure. Gremlin can do just about anything, but even for academic purposes, I don't think writing that query is worthwhile.

  • Related