# Create and Manage Indexes

Source: https://docs.formance.com/v4.0/modules/ledger/querying/indexes

Stack: v4.0

Ledger maintains a small set of read paths for every ledger and builds other indexes only when you request them. Start from a production query, identify the fields it uses, and create the corresponding indexes. Each additional index consumes storage, and adds work to the write path and to the historical backfill that makes the index usable.

The HTTP examples use the `LEDGER_URL`, `LEDGER_NAME`, and `CURL_AUTH` variables defined in [Read Ledger Data](https://docs.formance.com/v4.0/modules/ledger/querying/read-ledger-data), plus `jq`. The per-ledger HTTP routes for listing, inspecting, and checking an index require `ledger:LedgerRead`; creating and dropping one require `ledger:LedgerWrite`. Bucket-wide index inventory and status require `ledger:OpsRead`. See [Authentication and Authorization](https://docs.formance.com/v4.0/modules/ledger/operations/authentication).

## Choose the required index

| Query condition                 | Index to create                       | `ledgerctl --type`                     |
| ------------------------------- | ------------------------------------- | -------------------------------------- |
| Transaction reference           | Transaction reference                 | `reference`                            |
| Transaction effective timestamp | Transaction timestamp                 | `timestamp`                            |
| Transaction insertion time      | Transaction inserted-at               | `inserted-at`                          |
| Transaction reversal time       | Transaction reverted-at               | `reverted-at`                          |
| Any posting account             | Transaction address                   | `address`                              |
| Posting source account          | Transaction source address            | `source-address`                       |
| Posting destination account     | Transaction destination address       | `destination-address`                  |
| Account has held an asset       | Account asset                         | `account-asset`                        |
| Account or transaction metadata | Metadata for the exact target and key | `metadata` plus `--target` and `--key` |
| Ledger log date                 | Log date                              | REST canonical ID only                 |

Account address matching, transaction ID ranges, and transaction `reverted` checks do not require an opt-in index.

Metadata queries require two declarations in this order:

1. declare the metadata key and type in the ledger schema;
2. create an index for the same target and key.

See [Metadata and Typed Values](https://docs.formance.com/v4.0/modules/ledger/modeling/metadata) before indexing a metadata key whose existing values do not have one stable representation.

## Choose a management surface

Operator support is not in this preview

Operator-managed index configuration is not available in this Stack v4 preview. When your released Operator supports indexes, manage each index through one owner only and follow [Configuration as Code](https://docs.formance.com/v4.0/modules/ledger/operations/configuration-as-code). A reconciler will recreate a directly deleted index while its desired configuration still declares it.

Use the HTTP or `ledgerctl` workflows below to create, check, and remove an index.

## Create an index with ledgerctl

`ledgerctl` uses the gRPC administration surface:

```bash
ledgerctl indexes create --ledger "$LEDGER_NAME" --type reference
ledgerctl indexes create --ledger "$LEDGER_NAME" --type address
ledgerctl indexes create \
  --ledger "$LEDGER_NAME" \
  --type metadata \
  --target account \
  --key status
```

List the declared indexes and the readiness status reported by the contacted node:

```bash
ledgerctl indexes list --ledger "$LEDGER_NAME"
```

The command needs `ledger:LedgerRead` to list registry definitions. Its human-readable table also calls the bucket-wide gRPC status service, which requires `ledger:OpsRead`, to add the contacted replica's readiness status. Without `ledger:OpsRead`, the definitions remain available but the status column is `UNKNOWN`. Structured output such as `--json` returns only the registry definitions; use the per-ledger HTTP status route with `ledger:LedgerRead` when automation needs `currentVersion` or `pendingVersion`.

## Create an index with HTTP

The HTTP create and delete routes submit unsigned mutations. Ledger rejects them when `require_signatures=true`. In that mode, use `ledgerctl indexes create` and `ledgerctl indexes drop` through the signed gRPC `Apply` path, and configure the approved key and key ID in the CLI profile or with the global `--signing-key` and `--signing-key-id` options. See [Request and Response Signing](https://docs.formance.com/v4.0/modules/ledger/operations/signing).

The REST route accepts a canonical index ID. Capture the normalized ID returned by the successful `201` response:

```bash
REQUESTED_INDEX_ID='metadata:TARGET_TYPE_ACCOUNT:status'

INDEX_RESPONSE="$(curl --fail-with-body --silent --show-error \
  --request POST \
  "${CURL_AUTH[@]}" \
  --header "Content-Type: application/json" \
  --header "Idempotency-Key: create-$LEDGER_NAME-account-status-index" \
  --data "{\"id\":\"$REQUESTED_INDEX_ID\"}" \
  "$LEDGER_URL/v3/$LEDGER_NAME/indexes")"

INDEX_ID="$(jq -er '.data.id' <<<"$INDEX_RESPONSE")"
test "$INDEX_ID" = "$REQUESTED_INDEX_ID"
```

Common canonical IDs include:

```text
tx_builtin:TX_BUILTIN_INDEX_REFERENCE
tx_builtin:TX_BUILTIN_INDEX_TIMESTAMP
tx_builtin:TX_BUILTIN_INDEX_ADDRESS
tx_builtin:TX_BUILTIN_INDEX_SOURCE_ADDRESS
tx_builtin:TX_BUILTIN_INDEX_DESTINATION_ADDRESS
tx_builtin:TX_BUILTIN_INDEX_INSERTED_AT
tx_builtin:TX_BUILTIN_INDEX_REVERTED_AT
account_builtin:ACCT_BUILTIN_INDEX_ASSET
log_builtin:LOG_BUILTIN_INDEX_DATE
metadata:TARGET_TYPE_ACCOUNT:<key>
metadata:TARGET_TYPE_TRANSACTION:<key>
```

The `201` response returns the normalized canonical ID. Store that value for status, inspection, and deletion calls.

## Wait for readiness

Creating an index registers it and starts an asynchronous backfill. It does not make the index immediately available to queries.

```mermaid
flowchart LR
    Create["Create index"] --> Registered["Index registered"]
    Registered --> Backfill["Each replica backfills history"]
    Backfill --> Switch["Replica switches currentVersion"]
    Switch --> Ready["Query can use index on that replica"]
```

Poll the status route using the canonical ID returned at creation:

```bash
curl --fail-with-body --silent --show-error \
  "${CURL_AUTH[@]}" \
  "$LEDGER_URL/v3/$LEDGER_NAME/indexes/$INDEX_ID/status"
```

Interpret the version fields as follows:

| Field                | Meaning                                                                             |
| -------------------- | ----------------------------------------------------------------------------------- |
| `currentVersion: 0`  | The contacted replica cannot serve this index yet                                   |
| `currentVersion > 0` | The contacted replica can serve its current index version                           |
| `pendingVersion > 0` | That replica is building a newer version while continuing to serve `currentVersion` |

`ledgerctl indexes list --json` returns registry definitions only; they carry no readiness signal. Query execution uses the contacted replica's `currentVersion`, which only the status route reports.

Index status is local to the node that serves the request. In a multi-replica cluster, query each pod directly and wait for `currentVersion > 0` on every pod that can receive reads. Repeating one request through a load balancer does not prove that all replicas are ready.

Set `LEDGER_REPLICA_URLS` to endpoints that route directly to every Ledger pod that serves reads. Do not put a load-balanced URL in this list.

```bash
export LEDGER_REPLICA_URLS="https://ledger-0.internal.example.com https://ledger-1.internal.example.com https://ledger-2.internal.example.com"
```

Run the check and print the version observed on each replica:

```bash
ALL_READY=true
printf 'endpoint\tcurrent\tpending\tforward\n'

for endpoint in $LEDGER_REPLICA_URLS; do
  STATUS="$(curl --fail-with-body --silent --show-error \
    "${CURL_AUTH[@]}" \
    "$endpoint/v3/$LEDGER_NAME/indexes/$INDEX_ID/status")" || exit 1

  jq -r --arg endpoint "$endpoint" '
    .data
    | [$endpoint, .currentVersion, .pendingVersion,
       .index.forwardEncodingVersion]
    | @tsv
  ' <<<"$STATUS"

  if ! jq -e '.data.currentVersion > 0' <<<"$STATUS" >/dev/null; then
    ALL_READY=false
  fi
done

test "$ALL_READY" = true
```

For an initial build, the acceptance criterion is `current > 0` on every printed row and a final exit status of `0`. The version numbers can differ from the example below, but a completed initial build commonly looks like:

```text
endpoint                                      current  pending  forward
https://ledger-0.internal.example.com         1        0        1
https://ledger-1.internal.example.com         1        0        1
https://ledger-2.internal.example.com         1        0        1
```

Keep the pod-direct routing in deployment checks. Replacing these endpoints with one load-balanced address removes the per-replica guarantee.

Changing a metadata field declaration does not convert stored metadata values. When the declaration changes, replace the `jq` readiness condition inside the per-replica loop with this stricter criterion before depending on the new index encoding and comparison semantics:

```bash
jq -e '
  .data.currentVersion > 0
  and .data.pendingVersion == 0
  and .data.currentVersion == .data.index.forwardEncodingVersion
' <<<"$STATUS"
```

## Inspect a metadata index

Inspection answers data-modeling questions without changing the index. It is available only for metadata indexes whose current version is ready.

```bash
# Cardinality, min/max, and null/existence counts
ledgerctl indexes inspect \
  --ledger "$LEDGER_NAME" \
  --target account \
  --key status \
  --mode summary

# Values and counts
ledgerctl indexes inspect \
  --ledger "$LEDGER_NAME" \
  --target account \
  --key status \
  --mode facets \
  --page-size 100
```

The HTTP inspection modes are `summary`, `distinctValues`, and `facets`:

```bash
curl --fail-with-body --silent --show-error --get \
  "${CURL_AUTH[@]}" \
  --data-urlencode 'mode=facets' \
  --data-urlencode 'pageSize=100' \
  "$LEDGER_URL/v3/$LEDGER_NAME/indexes/$INDEX_ID/inspect"
```

`summary` scans the complete metadata index to compute its result. `distinctValues` and `facets` return a `nextCursor` page token when another page follows and a `previousCursor` when one precedes; send either back unchanged as `cursor`. Treat inspection as an operator or design-time tool, not as a high-frequency application query.

Built-in transaction, account, and log indexes cannot be inspected through this route.

## Remove an index safely

Before removing an index:

1. identify every direct and prepared query that uses it;
2. deploy callers that no longer issue those queries;
3. confirm that no reconciliation or reporting job still depends on it;
4. remove the index;
5. verify that the registry no longer lists it.

With `ledgerctl`, identify the same type, target, and key used at creation:

```bash
ledgerctl indexes drop \
  --ledger "$LEDGER_NAME" \
  --type metadata \
  --target account \
  --key status
```

With HTTP, delete by canonical ID:

```bash
curl --fail-with-body --silent --show-error \
  --request DELETE \
  "${CURL_AUTH[@]}" \
  --header "Idempotency-Key: drop-$LEDGER_NAME-account-status-index" \
  "$LEDGER_URL/v3/$LEDGER_NAME/indexes/$INDEX_ID"
```

Verify that the registry no longer resolves that exact ID:

```bash
HTTP_STATUS="$(curl --silent --show-error \
  --output /dev/null \
  --write-out '%{http_code}' \
  "${CURL_AUTH[@]}" \
  "$LEDGER_URL/v3/$LEDGER_NAME/indexes/$INDEX_ID")"

test "$HTTP_STATUS" = 404
```

An exit status of `0` confirms that the captured ID is absent. A different status means the deletion is not verified: check authentication, connectivity, and any configuration reconciler before continuing.

A caller that still depends on the removed index receives an index-not-found error. Recreating the index starts a new backfill; it does not restore immediate readiness.

## Diagnose index failures

| Result                           | Meaning                                                                                    | Action                                                                             |
| -------------------------------- | ------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------- |
| `INDEX_NOT_FOUND`                | The required index is not declared, or a metadata key is absent from the schema            | Declare the schema field and index for the exact query target                      |
| HTTP `503` with `INDEX_BUILDING` | The contacted replica has not switched to a usable version                                 | Retry with bounded backoff and inspect each serving replica                        |
| HTTP `409` on create             | An index with that identity already exists or the request conflicts                        | List indexes and reuse the existing canonical ID                                   |
| HTTP `400` on inspect            | The canonical ID is malformed, or the selected operation does not support a built-in index | Inspect metadata indexes only; treat a not-ready index as `INDEX_BUILDING` instead |

Continue with [Create Prepared Queries](https://docs.formance.com/v4.0/modules/ledger/querying/prepared-queries) when several callers must execute the same reviewed filter.
