I'm trying to use the LIMIT clause in Apache AGE to return a random number of rows from my graph database. Specifically, I want to return one to three rows at random, instead of a fixed number. I've tried using the toInteger(3 * rand()) + 1 expression in my query, but it's not working as expected. Can someone provide an example of how to use LIMIT to return a random number of rows in Apache AGE?
2 Answers
This query will return 1 to 3 columns:
SELECT * FROM cypher('demo', $$
UNWIND [1, 2, 3, 4, 5] AS n
RETURN n
LIMIT toInteger(3 * rand()) + 1
$$) AS (result agtype);
Here, you can find more information to read.

- 433
- 9
Keep in mind as per Docs, the rand() function generates a floating number on a approx. uniform distribution. So assuming you have a floating number of 0.38.... from the random function, as per your attempt.
It should come out to 1.14.. to integer -> 1.
Essentially your randomizing function can often generate the same number causing your function to fail to be truly random.
Use the following function to configure your randomizing digit.
SELECT *
FROM cypher('graph_name', $$
RETURN toInteger((10 * rand()) + 1)
$$) as (randomizer agtype);
For a 3 base a better approach is ->
toInteger((10 * (rand() + 0.13) + rand()) % 3 + 1)
The more random your randomizer is the better your chance of different results on each iteration/call.
EDIT: if you are doing this iteratively, perhaps you can add a variable that can be included in the randomizer.

- 224
- 8