Skip to main content

Use nested FOR loops for multi-level iteration

Nest FOR loops to perform operations across multiple collections simultaneously. This is particularly useful for creating relationships between all pairs of elements or processing hierarchical data structures.
Nested loops are executed for every combination of elements from the outer and inner collections, resulting in a cartesian product of operations.
Be mindful of performance when using nested loops with large collections. The number of operations grows multiplicatively with collection sizes (N × M operations for two collections).
When using the SDKs or curling the endpoint, the query name must match what is defined in the queries.hx file exactly.

Example 1: Creating connections between all user pairs

Here’s how to run the query using the SDKs or curl

Example 2: Cross-product operations with hierarchical data

Here’s how to run the query using the SDKs or curl

Performance considerations

Nested loops can significantly impact performance:
  • Two loops over collections of size N and M result in N × M operations
  • Three nested loops result in N × M × P operations
  • Consider using WHERE clauses to filter collections before looping
  • For large datasets, evaluate whether nested loops are the most efficient approach

Tips for optimizing nested loops:

  1. Filter early: Apply WHERE clauses before entering loops to reduce iteration count
  2. Consider alternatives: Sometimes traversals or joins can be more efficient than nested loops
  3. Batch operations: Group related operations to minimize database calls
  4. Monitor performance: Test with realistic data volumes to identify bottlenecks

Basic FOR Loops

Iterate over collections with simple variable binding

FOR Loop Destructuring

Extract multiple properties directly in loop variable binding