限制组中的结果数 (AQL)

Limit number of results in group (AQL)

我有以下有效的 AQL 查询:

FOR d IN task FILTER d.listId == @listId &&  d.appAccountId == @appAccountId &&  (@serviceId IN d.visibleOnTenants.tenants[*].serviceId || !d.visibleOnTenants.tenants)   
COLLECT groupId=d.status.statusId  INTO groupByType


SORT groupId 
RETURN {
        groupId,
        tasks: groupByType[*].d,
        tasksNo: LENGTH(groupByType[*].d)
    }

现在我想限制结果,但是对于每个组,假设每个 groupId 最多 10 个任务。 在 SORT groupId 之后有 LIMIT 0.10 限制组数,但我需要限制每个组的任务数。

有什么想法吗?

由于所有匹配的文档都已聚合,您可以执行一个简单的 SLICE() 从每个组中取出前 10 个元素:

RETURN {
    groupId,
    tasks: SLICE(groupByType, 0, 10)[*].d, // first 10
    tasksNo: LENGTH(groupByType[*].d)      // full count
}

另一个句法选项是使用 inline limit:

tasks: groupByType[* LIMIT 10].d,

使用标准 LIMIT 的最冗长变体是使用子查询:

tasks: (FOR g IN groupByType LIMIT 5 RETURN g.d),

子查询有自己的范围,LIMIT被限制在这个范围内。