I have a recursive data structure like so:
@Canonical
static class Person {
String name
Set<Person> knows
}
I have a Tinkerpop graph that represents this structure:
(Jon) -- knows --> (Billy) -- knows --> (Jane) -- ... -->
\- knows --> (Suzy) -- ... -->
What is the most efficient way to map an arbitrarily deep Tinkerpop graph to the data structure?
I can imagine the use of the PathStep
, but it seems like there should be a better way, and I am not grokking TP3 well enough to see it.
def 'build recursive person object'() {
when:
def g = TinkerGraph.open()
def jon = g.addVertex(T.label, 'person', 'name', 'jon')
def bill = g.addVertex(T.label, 'person', 'name', 'bill')
def jane = g.addVertex(T.label, 'person', 'name', 'jane')
jon.addEdge('knows', bill)
bill.addEdge('knows', jane)
Multimap<String, Person> relationships = HashMultimap.create()
g.V().has('name', 'jon')
.as('a')
.jump('b', { traverser -> !traverser.get().out('knows').hasNext() })
.outE('knows')
.inV()
.jump('a')
.as('b')
.path(
Function.<Vertex>identity(),
{ Edge e ->
relationships.put(e.outV().next().value('name') as String,
new Person(e.inV().next().value('name') as String))
} as Function
)
.next()
Person root = new Person('jon')
Stack<Person> people = new Stack<>()
Set<String> alreadySeen = new HashSet<>()
people.push(root)
alreadySeen.add('jon')
while(!people.isEmpty()) {
def person = people.pop()
person.knows = relationships.get(person.name)
for(Person related : person.knows) {
if(alreadySeen.add(related.name))
people.push(related)
}
}
then:
root.name == 'jon'
root.knows*.name == ['bill']
root.knows[0].knows*.name == ['jane']
}