Randomly select a document in ArangoDB
Asked Answered
M

2

7

Is there a way to randomly return a document from a collection using AQL?

I would like to create a random graph for testing purposes. I have not yet figured out how to select documents at random from the collection.

I was hoping I might be able to do something like this:

db._query('RETURN nodes[RAND(0..LENGTH(nodes))]').toArray()
JavaScript exception in file '/usr/share/arangodb/js/client/modules/org/arangodb/arangosh.js' at 104,11: [ArangoError 1541: invalid number of arguments for function 'RAND()', expected number of arguments: minimum: 0, maximum: 0 (while parsing)]
!    throw new ArangoError(requestResult);

Any thoughts on how to do this?

Meilen answered 2/3, 2015 at 21:22 Comment(0)
K
15

@yojimbo87 is right.

To select a random document from a collection you can instead do this:

FOR node IN nodes
  SORT RAND()
  LIMIT 1
  RETURN node

Collection objects in the JavaScript layer (arangosh/Foxx) also have a method for that:

var node = db.nodes.any();
Kratz answered 3/3, 2015 at 8:18 Comment(0)
T
4

As far as I know RAND() AQL function doesn't take any parameters and returns pseudo-random number between 0 and 1 which is why you are getting the error about invalid number of arguments.

Tacy answered 2/3, 2015 at 23:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.