> ## Documentation Index
> Fetch the complete documentation index at: https://docs.ditto.live/llms.txt
> Use this file to discover all available pages before exploring further.

# Reading Documents

> This article provides an overview of essential methods for reading documents within Ditto.

See [Document Model](/key-concepts/document-model) for more information on documents in Ditto.

Just like with conventional database querying, you execute query operations to fetch one or more documents that satisfy specific criteria and conditions.

To perform a single execution query on the Ditto store, call the `execute` API method on the `store` namespace as follows:

<CodeGroup>
  ```swift Swift theme={null}
  let result = await ditto.store.execute(query: "SELECT * FROM cars")
  ```

  ```kotlin Kotlin theme={null}
  // DittoQueryResult MUST be closed when you are done with it. Call result.close()
  // or use the Kotlin `use` block to auto-close results and items.
  ditto.store.execute("SELECT * FROM cars").use { result ->
      ...
  }
  ```

  ```javascript JS theme={null}
  const result = await ditto.store.execute("SELECT * FROM cars");
  ```

  ```typescript TypeScript theme={null}
  import { QueryResult } from '@dittolive/ditto';

  const result: QueryResult = await ditto.store.execute("SELECT * FROM cars");
  ```

  ```java Java theme={null}
  // This try-with-resources block auto-closes the DittoQueryResult
  try (DittoQueryResult result = ditto.getStore().execute(
          "SELECT * FROM cars"
      ).toCompletableFuture().join()) {
      ...
  }
  ```

  ```csharp C# theme={null}
  using var result = await ditto.Store.ExecuteAsync("SELECT * FROM cars");
  ```

  ```cpp C++ theme={null}
  auto result = ditto.get_store().execute("SELECT * FROM cars");
  ```

  ```rust Rust theme={null}
  let result = ditto.store().execute("SELECT * FROM cars").await?;
  ```

  ```dart Dart theme={null}
  final result = await ditto.store.execute("SELECT * FROM cars");
  ```

  ```go Go theme={null}
  result, err := dit.Store().Execute("SELECT * FROM cars")
  if err != nil {
      return err
  }
  defer result.Close()  // cleanup
  ```
</CodeGroup>

<Warning>
  **Critical Memory Management**: `QueryResult` and `QueryResultItem` objects should be treated like database cursors. Always extract the data you need immediately and then close/dematerialize them. Never store `QueryResult` or `QueryResultItem` instances directly between observer emissions as this will cause memory bloat and potential crashes.
</Warning>

## Using args to Query Dynamic Values

When dealing with data that may change dynamically during runtime, instead of defining the changing values directly in the query `string`, encapsulate them in a top-level `args` object you can use to reference the values in your queries.

To pass an argument to the `execute` function, use the `:[argument]` syntax with DQL where the `[argument]` maps to the field in the provided `args` object.

For example, here `color` is passed as an argument to the `execute` function, and, within the query string, `:color` placeholder references the `color` defined in a top-level `args` object.

<CodeGroup>
  ```swift Swift theme={null}
  let result = await ditto.store.execute(
    query: "SELECT * FROM cars WHERE color = :color",
    arguments: [ "color": "blue" ])
  ```

  ```kotlin Kotlin theme={null}
  ditto.store.execute(
    "SELECT * FROM cars WHERE color = :color",
    mapOf("color" to "blue")).use { result ->
        ...
    }
  ```

  ```javascript JS theme={null}
  const result = await ditto.store.execute(
    "SELECT * FROM cars WHERE color = :color",
    { color: "blue" }
  );
  ```

  ```typescript TypeScript theme={null}
  import { QueryResult } from '@dittolive/ditto';

  const result: QueryResult = await ditto.store.execute(
    "SELECT * FROM cars WHERE color = :color",
    { color: "blue" }
  );
  ```

  ```java Java theme={null}
  import static com.ditto.java.serialization.DittoCborSerializable.buildDictionary;

  // This try-with-resources block auto-closes the DittoQueryResult
  try (DittoQueryResult result = ditto.getStore().execute(
          "SELECT * FROM cars WHERE color = :color",
          buildDictionary().put("color", "blue").build()
      ).toCompletableFuture().join()) {
      ...
  }
  ```

  ```csharp C# theme={null}
  using var result = await ditto.Store.ExecuteAsync(
    "SELECT * FROM cars WHERE color = :color",
    new Dictionary<string, object> { "color", "blue" });
  ```

  ```cpp C++ theme={null}
  auto result = ditto.get_store().execute(
    "SELECT * FROM cars WHERE color = :color",
    {{"color", "blue"}});
  ```

  ```rust Rust theme={null}
  #[derive(serde::Serialize)]
  struct Args {
      color: String,
  }

  //...

  let args = Args {
      color: "blue".to_string(),
  };

  let result = ditto.store().execute((
    "SELECT * FROM cars WHERE color = :color",
    args,
  )).await?;
  ```

  ```dart Dart theme={null}
  final result = await ditto.store.execute(
    "SELECT * FROM cars WHERE color = :color",
    arguments: {"color": "blue"},
  );
  ```

  ```go Go theme={null}
  result, err := dit.Store().Execute(
  	"SELECT * FROM cars WHERE color = :color",
  	ditto.QueryArguments{"color": "blue"},
  )
  if err != nil {
      return err
  }
  defer result.Close()  // cleanup
  ```
</CodeGroup>

Once the previous example operation executes, the query becomes `SELECT * FROM cars WHERE color = blue`.

## Managing Query Results

After executing a query, the `result` object that is returned includes both the overall content retrieved and individual items. Each item is encapsulated in independent `QueryResultItem` objects that you can use to access them either directly or as raw CBOR or JSON data.

Rather than retrieving the items as part of the query execution and making them available immediately after execution, each item is *lazy loaded*. Lazy loading involves postponing fetching and storing in memory until requested on-demand or accessed later.

Here is an example query execution to select all documents from the `cars` collection. The result is stored in the variable result. Then, each item is lazy loaded from the result object and stored in the `items`:

<CodeGroup>
  ```swift Swift theme={null}

  let result = await ditto.store.execute(query: "SELECT * FROM cars")

  let items = result.items
  ```

  ```kotlin Kotlin theme={null}
  ditto.store.execute("SELECT * FROM cars").use { result ->
      const items = result.items
  }
  ```

  ```javascript JS theme={null}
  const result = await ditto.store.execute("SELECT * FROM cars")

  const items = result.items
  ```

  ```typescript TypeScript theme={null}
  import { QueryResult, QueryResultItem } from '@dittolive/ditto';

  const result: QueryResult = await ditto.store.execute("SELECT * FROM cars");

  const items: QueryResultItem[] = result.items;
  ```

  ```java Java theme={null}
  // This try-with-resources block auto-closes the DittoQueryResult
  try (DittoQueryResult result = ditto.getStore().execute(
          "SELECT * FROM cars"
      ).toCompletableFuture().join()) {
      List<DittoQueryResultItem> items = result.getItems();
  }
  ```

  ```csharp C# theme={null}
  using var result = await ditto.Store.ExecuteAsync("SELECT * FROM cars");

  var items = result.Items;
  ```

  ```cpp C++ theme={null}
  auto result = ditto.get_store().execute("SELECT * FROM cars");

  auto items = result.items();
  ```

  ```rust Rust theme={null}
  let result = ditto.store().execute("SELECT * FROM cars").await?;

  let items: Vec<_> = result.iter().collect();
  ```

  ```dart Dart theme={null}
  final result = await ditto.store.execute("SELECT * FROM cars");

  final items = result.items;
  ```

  ```go Go theme={null}
  result, _ := dit.Store().Execute("SELECT * FROM cars", nil)
  if err != nil {
      return err
  }
  defer result.Close()  // cleanup

  items := result.Items()
  ```
</CodeGroup>

## Working with a QueryResultItem

The result `items` object is a collection of`QueryResultItem`. Each item's value can be independently managed to meet the needs of your scenario.

### Value

To retrieve the value, call the `value` property on an item:

<CodeGroup>
  ```swift Swift theme={null}
  let result = await ditto.store.execute(query: "SELECT * FROM cars")

  let item = result.items[0]
  let itemValue = item.value
  let itemValueColor = item.value["color"]
  ```

  ```kotlin Kotlin theme={null}
  ditto.store.execute("SELECT * FROM cars").use { result ->
      val item = result.items.first()
      val itemValue = item.value
      val itemValueColor = item.value["color"]
  }
  ```

  ```javascript JS theme={null}
  const result = await ditto.store.execute(`SELECT * FROM cars`)

  const item = result.items[0]
  const itemValue = item.value
  const itemValueColor = item.value["color"]
  ```

  ```typescript TypeScript theme={null}
  import { QueryResult, QueryResultItem } from '@dittolive/ditto';

  interface Car {
    _id: string;
    color: string;
  }

  const result: QueryResult = await ditto.store.execute("SELECT * FROM cars");

  const item: QueryResultItem = result.items[0];
  const itemValue = item.value as Car;
  const itemValueColor: string = itemValue.color;
  ```

  ```java Java theme={null}
  import com.ditto.java.serialization.DittoCborSerializable;

  // This try-with-resources block auto-closes the DittoQueryResult
  try (DittoQueryResult result = ditto.getStore().execute(
          "SELECT * FROM cars"
      ).toCompletableFuture().join()) {
      DittoQueryResultItem item = result.getItems().get(0);
      DittoCborSerializable.Dictionary itemValue = item.getValue();
      String itemValueColor = itemValue.get("color").getString();
  }
  ```

  ```csharp C# theme={null}
  using var result = await ditto.Store.ExecuteAsync("SELECT * FROM cars");

  var item = result.Items[0];
  var itemValue = item.Value;
  var itemValueColor = item.Value["color"] as string;
  ```

  ```cpp C++ theme={null}
  const auto result = ditto.store.execute(`SELECT * FROM cars`);

  auto item = result.get_item(0);
  auto item_value = item.value();
  auto item_value_color = item_value["color"];
  ```

  ```rust Rust theme={null}
  let result = ditto.store().execute("SELECT * FROM cars").await?;

  let item = result.get_item(0).unwrap();
  let item_value = item.value();
  ```

  ```dart Dart theme={null}
  final result = await ditto.store.execute("SELECT * FROM cars");

  final item = result.items[0];
  final itemValue = item.value;
  final itemValueColor = item.value["color"];
  ```

  ```go Go theme={null}
  result, err := dit.Store().Execute("SELECT * FROM cars")
  if err != nil {
      return err
  }
  defer result.Close() // cleanup

  item := result.Item(0)
  defer item.Close()  // cleanup

  itemValue := item.Value()
  itemValueColor := itemValue["color"]
  ```
</CodeGroup>

### Materializing the Value

To help manage memory usage more efficiently, content associated with an `item` is lazily loaded, meaning it materializes — loads into memory — only upon the initial call to `value`.

To load the item's value into memory, use any of the following methods as appropriate:

<CodeGroup>
  ```swift Swift theme={null}

  // Returns `true` if value is currently held materialized in memory, otherwise returns `false`
  item.isMaterialized

  // Loads the item's value into memory
  item.materialize()

  // Release item's value from memory
  item.dematerialize()
  ```

  ```kotlin Kotlin theme={null}
  // Returns `true` if value is currently held materialized in memory, otherwise returns `false`
  item.isMaterialized

  // Loads the item's value into memory
  item.materialize()

  // Release item's value from memory
  item.dematerialize()
  ```

  ```javascript JS theme={null}
  // Returns `true` if value is currently held materialized in memory, otherwise returns `false`
  item.isMaterialized

  // Loads the item's value into memory
  item.materialize()

  // Release item's value from memory
  item.dematerialize()
  ```

  ```typescript TypeScript theme={null}
  // Returns `true` if value is currently held materialized in memory, otherwise returns `false`
  item.isMaterialized

  // Loads the item's value into memory
  item.materialize()

  // Release item's value from memory
  item.dematerialize()
  ```

  ```java Java theme={null}
  // Returns `true` if value is currently held materialized in memory, otherwise returns `false`
  item.isMaterialized

  // Loads the item's value into memory
  item.materialize()

  // Release item's value from memory
  item.dematerialize()
  ```

  ```csharp C# theme={null}
  // Returns `true` if value is currently held materialized in memory, otherwise returns `false`
  item.IsMaterialized;

  // Loads the item's value into memory
  item.Materialize();

  // Release item's value from memory
  item.Dematerialize();
  ```

  ```cpp C++ theme={null}
  // Returns `true` if value is currently held materialized in memory, otherwise returns `false`
  item.is_materialized()

  // Loads the item's value into memory
  item.materialize()

  // Release item's value from memory
  item.dematerialize()
  ```

  ```rust Rust theme={null}
  // Loads the item's value into memory
  item.materialize();
  ```

  ```dart Dart theme={null}
  // Query results are always materialized in Dart
  ```

  ```go Go theme={null}
  // Returns `true` if value is currently held materialized in memory, otherwise returns `false`
  item.IsMaterialized()

  // Loads the item's value into memory
  item.Materialize()

  // Release item's value from memory
  item.Dematerialize()
  ```
</CodeGroup>

### Raw CBOR Value

To access the result items as CBOR data:

<Info>
  The result of this method call is not cached.
</Info>

<CodeGroup>
  ```swift Swift theme={null}

  let result = await ditto.store.execute(query: "SELECT * FROM cars")

  let cborSerializedItem = result.items[0].cborData()
  ```

  ```kotlin Kotlin theme={null}
  ditto.store.execute("SELECT * FROM cars").use { result ->
      val cborItem = result.items.first().cborData()
  }
  ```

  ```javascript JS theme={null}
  const result = await ditto.store.execute(`SELECT * FROM cars`)

  const cborItem = result.items[0].cborData()
  ```

  ```typescript TypeScript theme={null}
  import { QueryResult } from '@dittolive/ditto';

  const result: QueryResult = await ditto.store.execute("SELECT * FROM cars");

  const cborItem: Uint8Array = result.items[0].cborData();
  ```

  ```java Java theme={null}
  // This try-with-resources block auto-closes the DittoQueryResult
  try (DittoQueryResult result = ditto.getStore().execute(
          "SELECT * FROM cars"
      ).toCompletableFuture().join()) {
      byte[] cborItem = result.getItems().get(0).cborData();
  }
  ```

  ```csharp C# theme={null}
  using var result = await ditto.Store.ExecuteAsync("SELECT * FROM cars");

  var cborItem = result.Items[0].CborData();
  ```

  ```cpp C++ theme={null}
  auto result = ditto.get_store().execute("SELECT * FROM cars");

  auto cborItem = result.get_item(0).cbor_data();
  ```

  ```rust Rust theme={null}
  let result = ditto.store().execute("SELECT * FROM cars").await?;

  let cborItem = result.get_item(0).unwrap().cbor_data();
  ```

  ```dart Dart theme={null}
  // Coming Soon
  ```

  ```go Go theme={null}
  result, err := dit.Store().Execute("SELECT * FROM cars")
  if err != nil {
      return err
  }
  defer result.Close()  // cleanup

  item := result.Item(0)
  defer item.Close()  // cleanup

  cborItem := item.CBORData()
  ```
</CodeGroup>

### Raw JSON Value

To access the result items as a JSON-string:

<Info>
  The result of this method call is not cached.
</Info>

<CodeGroup>
  ```swift Swift theme={null}

  let result = await ditto.store.execute(query: "SELECT * FROM cars")

  let jsonSerializedItem: String = result.items[0].jsonString()

  let jsonAsData: Data = Data(jsonSerializedItem.utf8)
  ```

  ```kotlin Kotlin theme={null}
  ditto.store.execute("SELECT * FROM cars").use { result ->  // Auto-closes result when done
      val jsonItem = result.items.first().jsonString()
  }
  ```

  ```javascript JS theme={null}
  const result = await ditto.store.execute(`SELECT * FROM cars`)

  const jsonItem = result.items[0].jsonString()
  ```

  ```typescript TypeScript theme={null}
  import { QueryResult } from '@dittolive/ditto';

  const result: QueryResult = await ditto.store.execute("SELECT * FROM cars");

  const jsonItem: string = result.items[0].jsonString();
  ```

  ```java Java theme={null}
  // This try-with-resources block auto-closes the DittoQueryResult
  try (DittoQueryResult result = ditto.getStore().execute(
          "SELECT * FROM cars"
      ).toCompletableFuture().join()) {
      String jsonItem = result.getItems().get(0).jsonString();
  }
  ```

  ```csharp C# theme={null}
  using var result = await ditto.Store.ExecuteAsync("SELECT * FROM cars");
  var jsonItem = result.Items[0].JsonString();
  ```

  ```cpp C++ theme={null}
  auto result = ditto.get_store().execute("SELECT * FROM cars");

  auto jsonItem = result.get_item(0).json_string();
  ```

  ```rust Rust theme={null}
  let result = ditto.store().execute("SELECT * FROM cars").await?;

  let jsonItem = result.get_item(0).unwrap().json_string();
  ```

  ```dart Dart theme={null}
  // Coming Soon
  ```

  ```go Go theme={null}
  result, err := dit.Store().Execute("SELECT * FROM cars")
  if err != nil {
      return err
  }
  defer result.Close()  // cleanup

  item := result.Item(0)
  defer item.Close()  // cleanup

  jsonAsBytes := item.JSONData()

  jsonAsString := item.JSONString()
  ```
</CodeGroup>
