gremlin: limit step vs take step

Viewed 215

I am new to gremlin and while referring to this website, I came across take() step. It has the same output as limit() which makes me wonder what is the difference between the two. I am unable to find any clarification regarding this matter. Thanks!

2 Answers

Unfortunately that's a bit confusing. take() is not a Gremlin step. It is instead a Groovy function that is being applied to the end of a traversal (which itself is an Iterator). In much the same way that you can use take() at then end of a traversal you can use other Groovy functions:

gremlin> g.V().take(1)
==>v[1]
gremlin> g.V().collect{it.value('name')}
==>marko
==>vadas
==>lop
==>josh
==>ripple
==>peter

Of course, once you use a Groovy function to process the pipeline you can't go back to Gremlin steps:

gremlin> g.V().take(1).out()
No signature of method: org.codehaus.groovy.runtime.DefaultGroovyMethods$TakeIterator.out() is applicable for argument types: () values: []
Possible solutions: sum(), sort(), sort(groovy.lang.Closure), sort(java.util.Comparator), count(java.lang.Object), count(groovy.lang.Closure)
Type ':help' or ':h' for help.
Display stack trace? [yN]

which is why you would prefer limit(1):

gremlin> g.V().limit(1).out()
==>v[3]
==>v[2]
==>v[4]

Of course, if you're not using Groovy and are programming in a Java environment then it would be obvious that take() and other such functions aren't going to be available to you.

The limit() step should be used and is, as of TinkerPop 3.4, the canonical way to iterate a Traversal and retrieve the first n elements.

I can't remember why take() was available on Traversal instances at the time of writing of this article. This sounds a bit odd to me; it could be an Iterator (or comparable) interface leaking, but I'll let maintainers comment on this if they read this question.

You'll be safe with limit().

Related