Sanka Darshana
Sanka Darshana

Reputation: 1421

Getting index of the resultset

Is there a way to get the index of the results within an aql query?

Something like FOR user IN Users sort user.age DESC RETURN {id:user._id, order:{index?}}

Upvotes: 2

Views: 195

Answers (2)

CodeManX
CodeManX

Reputation: 11885

If you want to enumerate the result set and store these numbers in an attribute order, then this is possible with the following AQL query:

LET sorted_ids = (
  FOR user IN Users
    SORT user.age DESC
    RETURN user._key
)
FOR i IN 0..LENGTH(sorted_ids)-1
  UPDATE sorted_ids[i] WITH { order: i+1 } IN Users
  RETURN NEW

A subquery is used to sort users by age and return an array of document keys. Then a loop over a numeric range from the first to the last index of the that array is used to iterate over its elements, which gives you the desired order value (minus 1) as variable i. The current array element is a document key, which is used to update the user document with an order attribute.

Above query can be useful for a one-off computation of an order attribute. If your data changes a lot, then it will quickly become stale however, and you may want to move this to the client-side.

For a related discussion see AQL: Counter / enumerator

Upvotes: 2

itsezc
itsezc

Reputation: 782

If I understand your question correctly - and feel free to correct me, this is what you're looking for:

FOR user IN Users
    SORT user.age DESC
    RETURN {
                id: user._id,
                order: user._key
            }

The _key is the primary key in ArangoDB.

If however, you're looking for example data entered (in chronological order) then you will have to have to set the key on your inserts and/or create a date / time object and filter using that.

Edit:

Upon doing some research, I believe this link might be of use to you for AI the keys: https://www.arangodb.com/2013/03/auto-increment-values-in-arangodb/

Upvotes: 0

Related Questions