4

Let's say I have two nodes 'A' and 'B' in graph with each node having 'name' (string) and 'roll-no' (int) properties. How can I write the query to get the node properties information in below format. Please note that I don't need data type information and nested json structure in the output.

[{name=[apple], roll-no=[10,20]}, {name=[mango], roll-no=[30]}]

I think I'm asking for how to convert GraphSON to normal JSON.

jbmusso
  • 3,436
  • 1
  • 25
  • 36

1 Answers1

4

You can project() the element into a Map:

gremlin> g.V(1).project('name','age').by('name').by('age')
==>[name:marko,age:29]

As you can see, taking this approach allows you to control how the map is produced in a more fine grained fashion as you control the properties in the by() step modulators. If the returned vertices do not have homogeneous property keys you will need to account for that in some way - here's one possibility:

gremlin> g.V().project('name','age').
......1>   by('name').
......2>   by(coalesce(values('age'),constant('none')))
==>[name:marko,age:29]
==>[name:vadas,age:27]
==>[name:lop,age:none]
==>[name:josh,age:32]
==>[name:ripple,age:none]
==>[name:peter,age:35]

Without using project you might also do something like this:

gremlin> g.V().local(properties().group().by(key()).by(value()))
==>[name:marko,age:29]
==>[name:vadas,age:27]
==>[name:lop,lang:java]
==>[name:josh,age:32]
==>[name:ripple,lang:java]
==>[name:peter,age:35]

Not quite as clear as project() and will get all properties which is generally discouraged, but obviously that approach will work. I guess you could itemize the properties to get though as follows:

gremlin> g.V().local(properties('name','age').group().by(key()).by(value()))
==>[name:marko,age:29]
==>[name:vadas,age:27]
==>[name:lop]
==>[name:josh,age:32]
==>[name:ripple]
==>[name:peter,age:35]
stephen mallette
  • 45,298
  • 5
  • 67
  • 135
  • It works for a single node but not for multiple nodes. g.V().project('name','age').by('name').by('age') – user1689963 Dec 19 '17 at 19:15
  • it will work for multiple vertices, but you have to account for vertices which might not have a particular property. Updated my answer a bit. – stephen mallette Dec 19 '17 at 20:06
  • `project()` is good if you need to take missing properties into account, otherwise I would just use `valueMap("name","age")`. `properties(...).group().by(...)` looks a bit overcomplicated to me. – Daniel Kuppitz Dec 21 '17 at 05:01
  • `valueMap()` doesn't work in this case. the question was about getting rid of the underlying multi-property wrapping in the map. – stephen mallette Dec 21 '17 at 11:54