0

Here's how my graph looks like.

g = TinkerGraph.open().traversal()
school1 = g.addV('school').property('id', '1').next()
school2 = g.addV('school').property('id', '2').next()
student1 = g.addV('student').property('id', '3').next() 
student2 = g.addV('student').property('id', '4').next()     
g.addE('students').from(school1).to(student1)
g.addE('students').from(school1).to(student2)
g.addE('students').from(school2).to(student1)

I want to find the out the students who are common to both the schools. To extend the logic, what'll happen if I want to write a generic infinite traversal logic for the same.

Jason Plurad
  • 6,682
  • 2
  • 18
  • 37
Pranjal
  • 500
  • 6
  • 12

2 Answers2

2
gremlin> g.V(school1).out('students').filter(__.in('students').is(school2)).valueMap(true)
==>[id:4,label:student,id:[3]]

Not sure what you mean by "write a generic infinite traversal logic for the same" though.

Daniel Kuppitz
  • 10,846
  • 1
  • 25
  • 34
  • This is what I meant by infinite generic traversal logic - g.V().has('tag', 'dev').hasLabel('school').has('id', '1').repeat(out().simplePath()).until(inE('students')).dedup().filter(__.repeat(in_().simplePath()).until(outE().outV().hasLabel('school').has('id', '2))) – Pranjal Oct 29 '18 at 12:54
0

This can work

gremlin> schools = [ '1', '2' ]
==>1
==>2
gremlin> g.V().
......1>   has('school', 'id', within(schools)).
......2>   out('students').
......3>   groupCount().by('id').
......4>   unfold().
......5>   filter( select(values).is(eq(schools.size())) ).
......6>   select(keys)
==>3
  • Start with the list of schools. It's probably safe to assume that there would be fewer schools than students.
  • Traverse out() from the schools to the students. At this point, a student appear multiple times in the stream, once for each school they attended. I'm assuming that there would be only 1 edge between a specific school and a specific student.
  • Do a groupCount() to create a Map where for each entry, the key is the student id and the value is the number of schools for the student.
  • Use unfold() to operate on the entries in the Map.
  • The filter picks only the students connected to all school in the lists, i.e. the student's value count equals the number of schools in the list.
  • Finally select(keys) to return the student id as the result.
Jason Plurad
  • 6,682
  • 2
  • 18
  • 37