3

I'm still at my earlier stages with graphs and gremlin.

Is it possible to randomly select graph vertices in Gremlin?

Consider the following pipeline that gets the cars owned by a user's friend:

u.out('Friend')[0..9].out('Drives').map()

But this code is only executed against the first 10 friends every time. How can I make the selection random efficiently?

Thank you for your time :)

riflehawk
  • 157
  • 8
  • Seems we could create a general purpose pipe that takes the desired number of elements as an argument and iterates through all input and then returns that number of randomly selected elements. – Paul Jackson Feb 25 '15 at 15:19

2 Answers2

6

In Gremlin 2.x you could use random step as in:

g.v(1).out.random()

or in 3.x random has become coin:

as in:

g.V(1).out.coin()

in 3.x, you might also look at sample and order(shuffle) steps in 3.x.

stephen mallette
  • 45,298
  • 5
  • 67
  • 135
1

You could use shuffle:

 g = TinkerGraphFactory.createTinkerGraph()
 gremlin> g.v(1).out.shuffle[0]
 ==>v[3]
 gremlin> g.v(1).out.shuffle[0]
 ==>v[2]
 gremlin> g.v(1).out.shuffle[0]
 ==>v[3]
 gremlin> g.v(1).out.shuffle[0]
 ==>v[4]

This solution isn't very efficient though since all neighbours of v(1) need to be fetched.

This might help as well: Random Walk on Bipartite Graph with Gremlin

Community
  • 1
  • 1
Faber
  • 1,504
  • 2
  • 13
  • 21