> ## Documentation Index
> Fetch the complete documentation index at: https://helix-digitalocean.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Result Operations

> Transform and organize traversal results using `COUNT`, `RANGE`, and `ORDER` operations.

## Count elements with `COUNT`  

Count the number of elements in a traversal.

```rust theme={null}
::COUNT
```

<Warning>
  When using the SDKs or curling the endpoint, the query name must match what is defined in the `queries.hx` file exactly.
</Warning>

### Example 1: Basic element counting

<CodeGroup>
  ```rust Query focus={1-3} [expandable] theme={null}
  QUERY GetUserCount () =>
      user_count <- N<User>::COUNT
      RETURN user_count

  QUERY CreateUser (name: String, age: U8, email: String) =>
      user <- AddN<User>({
          name: name,
          age: age,
          email: email
      })
      RETURN user
  ```

  ```rust Schema theme={null}
  N::User {
      name: String,
      age: U8,
      email: String
  }
  ```
</CodeGroup>

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

<CodeGroup>
  ```python Python [expandable] theme={null}
  from helix.client import Client

  client = Client(local=True, port=6969)

  users = [
      {"name": "Alice", "age": 25, "email": "alice@example.com"},
      {"name": "Bob", "age": 30, "email": "bob@example.com"},
      {"name": "Charlie", "age": 28, "email": "charlie@example.com"},
      {"name": "Diana", "age": 22, "email": "diana@example.com"},
  ]

  for user in users:
      client.query("CreateUser", user)

  result = client.query("GetUserCount", {})
  print(f"Total users: {result}")
  ```

  ```rust Rust [expandable] theme={null}
  use helix_rs::{HelixDB, HelixDBClient};
  use serde_json::json;

  #[tokio::main]
  async fn main() -> Result<(), Box<dyn std::error::Error>> {
      let client = HelixDB::new(Some("http://localhost"), Some(6969), None);

      let users = vec![
          ("Alice", 25, "alice@example.com"),
          ("Bob", 30, "bob@example.com"),
          ("Charlie", 28, "charlie@example.com"),
          ("Diana", 22, "diana@example.com"),
      ];

      for (name, age, email) in &users {
          let _created: serde_json::Value = client.query("CreateUser", &json!({
              "name": name,
              "age": age,
              "email": email,
          })).await?;
      }

      let result: serde_json::Value = client.query("GetUserCount", &json!({})).await?;
      println!("Total users: {result:#?}");

      Ok(())
  }
  ```

  ```go Go [expandable] theme={null}
  package main

  import (
      "fmt"
      "log"

      "github.com/HelixDB/helix-go"
  )

  func main() {
      client := helix.NewClient("http://localhost:6969")

      users := []map[string]any{
          {"name": "Alice", "age": uint8(25), "email": "alice@example.com"},
          {"name": "Bob", "age": uint8(30), "email": "bob@example.com"},
          {"name": "Charlie", "age": uint8(28), "email": "charlie@example.com"},
          {"name": "Diana", "age": uint8(22), "email": "diana@example.com"},
      }

      for _, user := range users {
          var created map[string]any
          if err := client.Query("CreateUser", helix.WithData(user)).Scan(&created); err != nil {
              log.Fatalf("CreateUser failed: %s", err)
          }
      }

      var result map[string]any
      if err := client.Query("GetUserCount", helix.WithData(map[string]any{})).Scan(&result); err != nil {
          log.Fatalf("GetUserCount failed: %s", err)
      }

      fmt.Printf("Total users: %#v\n", result)
  }
  ```

  ```typescript TypeScript [expandable] theme={null}
  import HelixDB from "helix-ts";

  async function main() {
      const client = new HelixDB("http://localhost:6969");

      const users = [
          { name: "Alice", age: 25, email: "alice@example.com" },
          { name: "Bob", age: 30, email: "bob@example.com" },
          { name: "Charlie", age: 28, email: "charlie@example.com" },
          { name: "Diana", age: 22, email: "diana@example.com" },
      ];

      for (const user of users) {
          await client.query("CreateUser", user);
      }

      const result = await client.query("GetUserCount", {});
      console.log("Total users:", result);
  }

  main().catch((err) => {
      console.error("GetUserCount query failed:", err);
  });
  ```

  ```bash Curl [expandable] theme={null}
  curl -X POST \
    http://localhost:6969/CreateUser \
    -H 'Content-Type: application/json' \
    -d '{"name":"Alice","age":25,"email":"alice@example.com"}'

  curl -X POST \
    http://localhost:6969/CreateUser \
    -H 'Content-Type: application/json' \
    -d '{"name":"Bob","age":30,"email":"bob@example.com"}'

  curl -X POST \
    http://localhost:6969/CreateUser \
    -H 'Content-Type: application/json' \
    -d '{"name":"Charlie","age":28,"email":"charlie@example.com"}'

  curl -X POST \
    http://localhost:6969/CreateUser \
    -H 'Content-Type: application/json' \
    -d '{"name":"Diana","age":22,"email":"diana@example.com"}'

  curl -X POST \
    http://localhost:6969/GetUserCount \
    -H 'Content-Type: application/json' \
    -d '{}'
  ```
</CodeGroup>

***

## Scope results with `RANGE`  

Get a specific range of elements from a traversal.

```rust theme={null}
::RANGE(start, end)
```

<Note>
  RANGE is inclusive of the start but exclusive of the end. For example, RANGE(0, 10) returns elements 0 through 9 (10 total elements). Both start and end and required and must be positive integers.
</Note>

<Warning>
  When using the SDKs or curling the endpoint, the query name must match what is defined in the `queries.hx` file exactly.
</Warning>

### Example 1: Basic pagination

<CodeGroup>
  ```rust Query focus={1-3} [expandable] theme={null}
  QUERY GetUsersPaginated (start: U32, end: U32) =>
      users <- N<User>::RANGE(start, end)
      RETURN users

  QUERY CreateUser (name: String, age: U8, email: String) =>
      user <- AddN<User>({
          name: name,
          age: age,
          email: email
      })
      RETURN user
  ```

  ```rust Schema theme={null}
  N::User {
      name: String,
      age: U8,
      email: String
  }
  ```
</CodeGroup>

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

<CodeGroup>
  ```python Python [expandable] theme={null}
  from helix.client import Client

  client = Client(local=True, port=6969)

  for i in range(20):
      client.query("CreateUser", {
          "name": f"User{i}",
          "age": 20 + (i % 40),
          "email": f"user{i}@example.com"
      })

  page1 = client.query("GetUsersPaginated", {"start": 0, "end": 5})
  print("Page 1:", page1)

  page2 = client.query("GetUsersPaginated", {"start": 5, "end": 10})
  print("Page 2:", page2)

  page3 = client.query("GetUsersPaginated", {"start": 10, "end": 15})
  print("Page 3:", page3)
  ```

  ```rust Rust [expandable] theme={null}
  use helix_rs::{HelixDB, HelixDBClient};
  use serde_json::json;

  #[tokio::main]
  async fn main() -> Result<(), Box<dyn std::error::Error>> {
      let client = HelixDB::new(Some("http://localhost"), Some(6969), None);

      for i in 0..20 {
          let _created: serde_json::Value = client.query("CreateUser", &json!({
              "name": format!("User{}", i),
              "age": 20 + (i % 40),
              "email": format!("user{}@example.com", i),
          })).await?;
      }

      let page1: serde_json::Value = client.query("GetUsersPaginated", &json!({
          "start": 0,
          "end": 5
      })).await?;
      println!("Page 1: {page1:#?}");

      let page2: serde_json::Value = client.query("GetUsersPaginated", &json!({
          "start": 5,
          "end": 10
      })).await?;
      println!("Page 2: {page2:#?}");

      Ok(())
  }
  ```

  ```go Go [expandable] theme={null}
  package main

  import (
      "fmt"
      "log"

      "github.com/HelixDB/helix-go"
  )

  func main() {
      client := helix.NewClient("http://localhost:6969")

      for i := 0; i < 20; i++ {
          user := map[string]any{
              "name":  fmt.Sprintf("User%d", i),
              "age":   uint8(20 + (i % 40)),
              "email": fmt.Sprintf("user%d@example.com", i),
          }
          
          var created map[string]any
          if err := client.Query("CreateUser", helix.WithData(user)).Scan(&created); err != nil {
              log.Fatalf("CreateUser failed: %s", err)
          }
      }

      page1Payload := map[string]any{"start": uint32(0), "end": uint32(5)}
      var page1 map[string]any
      if err := client.Query("GetUsersPaginated", helix.WithData(page1Payload)).Scan(&page1); err != nil {
          log.Fatalf("GetUsersPaginated failed: %s", err)
      }
      fmt.Printf("Page 1: %#v\n", page1)

      page2Payload := map[string]any{"start": uint32(5), "end": uint32(10)}
      var page2 map[string]any
      if err := client.Query("GetUsersPaginated", helix.WithData(page2Payload)).Scan(&page2); err != nil {
          log.Fatalf("GetUsersPaginated failed: %s", err)
      }
      fmt.Printf("Page 2: %#v\n", page2)
  }
  ```

  ```typescript TypeScript [expandable] theme={null}
  import HelixDB from "helix-ts";

  async function main() {
      const client = new HelixDB("http://localhost:6969");

      for (let i = 0; i < 20; i++) {
          await client.query("CreateUser", {
              name: `User${i}`,
              age: 20 + (i % 40),
              email: `user${i}@example.com`
          });
      }

      const page1 = await client.query("GetUsersPaginated", {
          start: 0,
          end: 5
      });
      console.log("Page 1:", page1);

      const page2 = await client.query("GetUsersPaginated", {
          start: 5,
          end: 10
      });
      console.log("Page 2:", page2);

      const page3 = await client.query("GetUsersPaginated", {
          start: 10,
          end: 15
      });
      console.log("Page 3:", page3);
  }

  main().catch((err) => {
      console.error("GetUsersPaginated query failed:", err);
  });
  ```

  ```bash Curl [expandable] theme={null}
  curl -X POST \
    http://localhost:6969/CreateUser \
    -H 'Content-Type: application/json' \
    -d '{"name":"User0","age":20,"email":"user0@example.com"}'

  curl -X POST \
    http://localhost:6969/CreateUser \
    -H 'Content-Type: application/json' \
    -d '{"name":"User1","age":21,"email":"user1@example.com"}'

  curl -X POST \
    http://localhost:6969/GetUsersPaginated \
    -H 'Content-Type: application/json' \
    -d '{"start":0,"end":5}'

  curl -X POST \
    http://localhost:6969/GetUsersPaginated \
    -H 'Content-Type: application/json' \
    -d '{"start":5,"end":10}'
  ```
</CodeGroup>

***

## Sort results with `ORDER`  

Sort the results of a traversal by a property in ascending or descending order.

```rust theme={null}
::ORDER<Asc>(_::{property})
::ORDER<Desc>(_::{property})
```

<Note>
  Use `Asc` for ascending order and `Desc` for descending order.
</Note>

<Warning>
  When using the SDKs or curling the endpoint, the query name must match what is defined in the `queries.hx` file exactly.
</Warning>

### Example 1: Sorting by age (oldest first)

<CodeGroup>
  ```rust Query focus={1-3} [expandable] theme={null}
  QUERY GetUsersOldestFirst () =>
      users <- N<User>::ORDER<Desc>(_::{age})
      RETURN users

  QUERY CreateUser (name: String, age: U8, email: String) =>
      user <- AddN<User>({
          name: name,
          age: age,
          email: email
      })
      RETURN user
  ```

  ```rust Schema theme={null}
  N::User {
      name: String,
      age: U8,
      email: String
  }
  ```
</CodeGroup>

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

<CodeGroup>
  ```python Python [expandable] theme={null}
  from helix.client import Client

  client = Client(local=True, port=6969)

  users = [
      {"name": "Alice", "age": 25, "email": "alice@example.com"},
      {"name": "Bob", "age": 45, "email": "bob@example.com"},
      {"name": "Charlie", "age": 19, "email": "charlie@example.com"},
      {"name": "Diana", "age": 32, "email": "diana@example.com"},
      {"name": "Eve", "age": 28, "email": "eve@example.com"},
  ]

  for user in users:
      client.query("CreateUser", user)

  result = client.query("GetUsersOldestFirst", {})
  print("Users (oldest first):", result)
  ```

  ```rust Rust [expandable] theme={null}
  use helix_rs::{HelixDB, HelixDBClient};
  use serde_json::json;

  #[tokio::main]
  async fn main() -> Result<(), Box<dyn std::error::Error>> {
      let client = HelixDB::new(Some("http://localhost"), Some(6969), None);

      let users = vec![
          ("Alice", 25, "alice@example.com"),
          ("Bob", 45, "bob@example.com"),
          ("Charlie", 19, "charlie@example.com"),
          ("Diana", 32, "diana@example.com"),
          ("Eve", 28, "eve@example.com"),
      ];

      for (name, age, email) in &users {
          let _created: serde_json::Value = client.query("CreateUser", &json!({
              "name": name,
              "age": age,
              "email": email,
          })).await?;
      }

      let result: serde_json::Value = client.query("GetUsersOldestFirst", &json!({})).await?;
      println!("Users (oldest first): {result:#?}");

      Ok(())
  }
  ```

  ```go Go [expandable] theme={null}
  package main

  import (
      "fmt"
      "log"

      "github.com/HelixDB/helix-go"
  )

  func main() {
      client := helix.NewClient("http://localhost:6969")

      users := []map[string]any{
          {"name": "Alice", "age": uint8(25), "email": "alice@example.com"},
          {"name": "Bob", "age": uint8(45), "email": "bob@example.com"},
          {"name": "Charlie", "age": uint8(19), "email": "charlie@example.com"},
          {"name": "Diana", "age": uint8(32), "email": "diana@example.com"},
          {"name": "Eve", "age": uint8(28), "email": "eve@example.com"},
      }

      for _, user := range users {
          var created map[string]any
          if err := client.Query("CreateUser", helix.WithData(user)).Scan(&created); err != nil {
              log.Fatalf("CreateUser failed: %s", err)
          }
      }

      var result map[string]any
      if err := client.Query("GetUsersOldestFirst", helix.WithData(map[string]any{})).Scan(&result); err != nil {
          log.Fatalf("GetUsersOldestFirst failed: %s", err)
      }

      fmt.Printf("Users (oldest first): %#v\n", result)
  }
  ```

  ```typescript TypeScript [expandable] theme={null}
  import HelixDB from "helix-ts";

  async function main() {
      const client = new HelixDB("http://localhost:6969");

      const users = [
          { name: "Alice", age: 25, email: "alice@example.com" },
          { name: "Bob", age: 45, email: "bob@example.com" },
          { name: "Charlie", age: 19, email: "charlie@example.com" },
          { name: "Diana", age: 32, email: "diana@example.com" },
          { name: "Eve", age: 28, email: "eve@example.com" },
      ];

      for (const user of users) {
          await client.query("CreateUser", user);
      }

      const result = await client.query("GetUsersOldestFirst", {});
      console.log("Users (oldest first):", result);
  }

  main().catch((err) => {
      console.error("GetUsersOldestFirst query failed:", err);
  });
  ```

  ```bash Curl [expandable] theme={null}
  curl -X POST \
    http://localhost:6969/CreateUser \
    -H 'Content-Type: application/json' \
    -d '{"name":"Alice","age":25,"email":"alice@example.com"}'

  curl -X POST \
    http://localhost:6969/CreateUser \
    -H 'Content-Type: application/json' \
    -d '{"name":"Bob","age":45,"email":"bob@example.com"}'

  curl -X POST \
    http://localhost:6969/CreateUser \
    -H 'Content-Type: application/json' \
    -d '{"name":"Charlie","age":19,"email":"charlie@example.com"}'

  curl -X POST \
    http://localhost:6969/CreateUser \
    -H 'Content-Type: application/json' \
    -d '{"name":"Diana","age":32,"email":"diana@example.com"}'

  curl -X POST \
    http://localhost:6969/CreateUser \
    -H 'Content-Type: application/json' \
    -d '{"name":"Eve","age":28,"email":"eve@example.com"}'

  curl -X POST \
    http://localhost:6969/GetUsersOldestFirst \
    -H 'Content-Type: application/json' \
    -d '{}'
  ```
</CodeGroup>

### Example 2: Sorting by age (youngest first)

<CodeGroup>
  ```rust Query focus={1-3} [expandable] theme={null}
  QUERY GetUsersYoungestFirst () =>
      users <- N<User>::ORDER<Asc>(_::{age})
      RETURN users

  QUERY CreateUser (name: String, age: U8, email: String) =>
      user <- AddN<User>({
          name: name,
          age: age,
          email: email
      })
      RETURN user
  ```

  ```rust Schema theme={null}
  N::User {
      name: String,
      age: U8,
      email: String
  }
  ```
</CodeGroup>

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

<CodeGroup>
  ```python Python [expandable] theme={null}
  from helix.client import Client

  client = Client(local=True, port=6969)

  users = [
      {"name": "Alice", "age": 25, "email": "alice@example.com"},
      {"name": "Bob", "age": 45, "email": "bob@example.com"},
      {"name": "Charlie", "age": 19, "email": "charlie@example.com"},
      {"name": "Diana", "age": 32, "email": "diana@example.com"},
      {"name": "Eve", "age": 28, "email": "eve@example.com"},
  ]

  for user in users:
      client.query("CreateUser", user)

  result = client.query("GetUsersYoungestFirst", {})
  print("Users (youngest first):", result)
  ```

  ```rust Rust [expandable] theme={null}
  use helix_rs::{HelixDB, HelixDBClient};
  use serde_json::json;

  #[tokio::main]
  async fn main() -> Result<(), Box<dyn std::error::Error>> {
      let client = HelixDB::new(Some("http://localhost"), Some(6969), None);

      let users = vec![
          ("Alice", 25, "alice@example.com"),
          ("Bob", 45, "bob@example.com"),
          ("Charlie", 19, "charlie@example.com"),
          ("Diana", 32, "diana@example.com"),
          ("Eve", 28, "eve@example.com"),
      ];

      for (name, age, email) in &users {
          let _created: serde_json::Value = client.query("CreateUser", &json!({
              "name": name,
              "age": age,
              "email": email,
          })).await?;
      }

      let result: serde_json::Value = client.query("GetUsersYoungestFirst", &json!({})).await?;
      println!("Users (youngest first): {result:#?}");

      Ok(())
  }
  ```

  ```go Go [expandable] theme={null}
  package main

  import (
      "fmt"
      "log"

      "github.com/HelixDB/helix-go"
  )

  func main() {
      client := helix.NewClient("http://localhost:6969")

      users := []map[string]any{
          {"name": "Alice", "age": uint8(25), "email": "alice@example.com"},
          {"name": "Bob", "age": uint8(45), "email": "bob@example.com"},
          {"name": "Charlie", "age": uint8(19), "email": "charlie@example.com"},
          {"name": "Diana", "age": uint8(32), "email": "diana@example.com"},
          {"name": "Eve", "age": uint8(28), "email": "eve@example.com"},
      }

      for _, user := range users {
          var created map[string]any
          if err := client.Query("CreateUser", helix.WithData(user)).Scan(&created); err != nil {
              log.Fatalf("CreateUser failed: %s", err)
          }
      }

      var result map[string]any
      if err := client.Query("GetUsersYoungestFirst", helix.WithData(map[string]any{})).Scan(&result); err != nil {
          log.Fatalf("GetUsersYoungestFirst failed: %s", err)
      }

      fmt.Printf("Users (youngest first): %#v\n", result)
  }
  ```

  ```typescript TypeScript [expandable] theme={null}
  import HelixDB from "helix-ts";

  async function main() {
      const client = new HelixDB("http://localhost:6969");

      const users = [
          { name: "Alice", age: 25, email: "alice@example.com" },
          { name: "Bob", age: 45, email: "bob@example.com" },
          { name: "Charlie", age: 19, email: "charlie@example.com" },
          { name: "Diana", age: 32, email: "diana@example.com" },
          { name: "Eve", age: 28, email: "eve@example.com" },
      ];

      for (const user of users) {
          await client.query("CreateUser", user);
      }

      const result = await client.query("GetUsersYoungestFirst", {});
      console.log("Users (youngest first):", result);
  }

  main().catch((err) => {
      console.error("GetUsersYoungestFirst query failed:", err);
  });
  ```

  ```bash Curl [expandable] theme={null}
  curl -X POST \
    http://localhost:6969/CreateUser \
    -H 'Content-Type: application/json' \
    -d '{"name":"Alice","age":25,"email":"alice@example.com"}'

  curl -X POST \
    http://localhost:6969/CreateUser \
    -H 'Content-Type: application/json' \
    -d '{"name":"Bob","age":45,"email":"bob@example.com"}'

  curl -X POST \
    http://localhost:6969/CreateUser \
    -H 'Content-Type: application/json' \
    -d '{"name":"Charlie","age":19,"email":"charlie@example.com"}'

  curl -X POST \
    http://localhost:6969/CreateUser \
    -H 'Content-Type: application/json' \
    -d '{"name":"Diana","age":32,"email":"diana@example.com"}'

  curl -X POST \
    http://localhost:6969/CreateUser \
    -H 'Content-Type: application/json' \
    -d '{"name":"Eve","age":28,"email":"eve@example.com"}'

  curl -X POST \
    http://localhost:6969/GetUsersYoungestFirst \
    -H 'Content-Type: application/json' \
    -d '{}'
  ```
</CodeGroup>
