arangodb - 获取结果集的索引
问题描述
有没有办法在 aql 查询中获取结果的索引?
就像是
FOR user IN Users sort user.age DESC RETURN {id:user._id, order:{index?}}
解决方案
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
推荐阅读
- javascript - 如何在 React 中将数据从 Form 传递到 mapDispatchToProps
- c# - InvalidCastException:无法将“System.Guid”类型的对象转换为“System.String”类型。在 asp.net 核心 webapi 中
- python - matplotlib 中的径向热图
- c - 从没有 FPO 的定点整数重建 IEEE754 浮点二进制
- python - pyTelegramBot 装饰器未检测到更新
- python - 我们如何在使用 python 的滚动平均期间拒绝包含异常值的窗口?
- algorithm - Gnome 排序的优缺点是什么
- javascript - 在反应中将axios响应传递给子组件
- javascript - 根据元素中的特定关键字计算数组中的项目
- c# - 是否可以在图表中创建自定义 X 轴?