Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Randomly select a document in ArangoDB

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?

like image 423
mikewilliamson Avatar asked Mar 02 '15 21:03

mikewilliamson


People also ask

How do you query in ArangoDB?

The ArangoDB Query Language (AQL) can be used to retrieve and modify data that are stored in ArangoDB. The general workflow when executing a query is as follows: A client application ships an AQL query to the ArangoDB server. The query text contains everything ArangoDB needs to compile the result set.

What is AQL ArangoDB?

The ArangoDB Query Language (AQL) is similar to the Structured Query Language (SQL) in its purpose. Both support reading and modifying collection data, however AQL does not support data definition operations, such as creating and dropping databases, collections and indexes.

What are the three system attributes required for every document?

All documents contain special attributes: the document handle is stored as a string in _id , the document's primary key in _key and the document revision in _rev . The value of the _key attribute can be specified by the user when creating a document.


2 Answers

@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();
like image 69
stj Avatar answered Oct 14 '22 09:10

stj


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.

like image 36
yojimbo87 Avatar answered Oct 14 '22 09:10

yojimbo87