mirror of https://gitee.com/bigwinds/arangodb
53 lines
1.5 KiB
Plaintext
53 lines
1.5 KiB
Plaintext
!CHAPTER Advanced features
|
|
|
|
!SUBSECTION Subqueries
|
|
|
|
Wherever an expression is allowed in AQL, a subquery can be placed. A subquery
|
|
is a query part that can introduce its own local variables without affecting
|
|
variables and values in its outer scope(s).
|
|
|
|
It is required that subqueries be put inside parentheses *(* and *)* to
|
|
explicitly mark their start and end points:
|
|
|
|
```js
|
|
FOR u IN users
|
|
LET recommendations = (
|
|
FOR r IN recommendations
|
|
FILTER u.id == r.userId
|
|
SORT u.rank DESC
|
|
LIMIT 10
|
|
RETURN r
|
|
)
|
|
RETURN { "user" : u, "recommendations" : recommendations }
|
|
```
|
|
|
|
```js
|
|
FOR u IN users
|
|
COLLECT city = u.city INTO g
|
|
RETURN { "city" : city, "numUsers" : LENGTH(g), "maxRating": MAX(
|
|
FOR r IN g
|
|
RETURN r.user.rating
|
|
)}
|
|
```
|
|
|
|
Subqueries may also include other subqueries themselves.
|
|
|
|
!SUBSECTION Variable expansion
|
|
|
|
In order to access a named attribute from all elements in an array easily, AQL
|
|
offers the shortcut operator <i>[\*]</i> for variable expansion.
|
|
|
|
Using the <i>[\*]</i> operator with a variable will iterate over all elements in the
|
|
variable thus allowing to access a particular attribute of each element. It is
|
|
required that the expanded variable is an array. The result of the <i>[\*]</i>
|
|
operator is again an array.
|
|
|
|
```js
|
|
FOR u IN users
|
|
RETURN { "user" : u, "friendNames" : u.friends[*].name }
|
|
```
|
|
|
|
In the above example, the attribute *name* is accessed for each element in the
|
|
array *u.friends*. The result is a flat array of friend names, made available as
|
|
the attribute *friendNames*.
|