Passing dynamic value inside sample method in gremlin is not working
Asked Answered
Z

2

6

I am a newbie to the gremlin. I am trying to get some random vertices based on some condition. But if I am using sample method with some mathematical computation it is not working. But if I give integer values it is working fine.

The following query is working fine:

g.V().hasLabel('Person').sample(1)

The following query is not working:

g.V().hasLabel('Person').sample(math('4/2'))

Actually, based on the number of persons I should perform some mathematical computations inside sample method. Thanks in advance

Zeiger answered 3/9, 2020 at 7:30 Comment(0)
S
5

That's an interesting bit of Gremlin you are trying to run. I've not seen anyone try that before. Sadly, it won't work because sample() does not take a Traversal as an argument. It only takes a number. There is no workaround for this issue aside from doing the computation outside of Gremlin which isn't helpful if you need to choose your sample size based on data in your query. sample() isn't the only step that behaves this way. I've created TINKERPOP-2414 to track this issue.

Sardinia answered 3/9, 2020 at 12:5 Comment(2)
If not sample method, is there any other method or any way to pick some random vertices in a single query??Zeiger
you can use sample() but you can't dynamically calculate the number sampled by way of a Traversal. it is the dynamic calculation that is a problem. what is the nature of the calculation you hoped to do with math() step?Sardinia
M
0

All you need to do is: g.V().hasLabel('Person').sample(Math.round(4/2).intValue())

Gremlin is running in a groovy shell. When in doubt, you can check how to convert a Long into Integer so that the sample function which takes Integer as the argument can work.

Most answered 3/9, 2020 at 11:11 Comment(1)
I'd just like to clarify a bit by saying that Gremlin is not Groovy. It can run on Groovy in which case this sort of thing may work but it will not work (1) if the Gremlin is not running on the JVM or (2) if your calculation requires data from the running traversal. This approach does the calculation for sample prior to executing the traversal and is therefore static for the life of the traversal. If you needed a dynamic sample, there is no workaround.Sardinia

© 2022 - 2025 — McMap. All rights reserved.