首页 > 解决方案 > 获取结果集的索引

问题描述

有没有办法在 aql 查询中获取结果的索引?

就像是 FOR user IN Users sort user.age DESC RETURN {id:user._id, order:{index?}}

标签: arangodbaql

解决方案


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


推荐阅读