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

# Schema 概覽

> ChainStream GraphQL schema 的結構 — Chain Groups、Cube 欄位、生成型別與內省

## 動態 Schema 生成

ChainStream GraphQL schema 在啟動時由 **activecube-rs** **動態生成**。該 Rust 庫將 **Cube** 定義編譯為型別完整的 [async-graphql](https://github.com/async-graphql/async-graphql) schema。每個 Cube 對應由 OLAP 表支撐的分析資料模型，activecube-rs 會自動產出：

* Cube 的**頂層 Query 欄位**（巢狀在其 Chain Group 下）
* 表示可選維度的 **Record 型別**（`{Cube}Record`）
* 與維度層級一致的 **Filter 輸入**（`{Cube}Filter`）
* 每條維度路徑的 ASC/DESC 變體組成的 **OrderBy 列舉**（`{Cube}OrderBy`）

因此 schema 始終與底層資料模型一致——無需手寫 SDL 維護。

<Info>
  由於 schema 由 Cube 定義生成，Rust 中新增的資料模型在部署後會自動反映到 GraphQL 端點。
</Info>

***

## 根查詢結構

根查詢型別名為 `ChainStream`。Cube 歸入三個 **Chain Group**，每個作為頂層欄位暴露：

```graphql theme={null}
type ChainStream {
  EVM(network: Network!, dataset: Dataset, aggregates: Aggregates) {
    DEXTrades(...): [DEXTradesRecord!]!
    Transfers(...): [TransfersRecord!]!
    BalanceUpdates(...): [BalanceUpdatesRecord!]!
    Blocks(...): [BlocksRecord!]!
    Transactions(...): [TransactionsRecord!]!
    Events(...): [EventsRecord!]!
    Calls(...): [CallsRecord!]!
    # ... more EVM Cubes
  }

  Solana(dataset: Dataset, aggregates: Aggregates) {
    DEXTrades(...): [DEXTradesRecord!]!
    Instructions(...): [InstructionsRecord!]!
    DEXOrders(...): [DEXOrdersRecord!]!
    # ... more Solana Cubes
  }

  Trading(dataset: Dataset, aggregates: Aggregates) {
    Pairs(...): [PairsRecord!]!
    Tokens(...): [TokensRecord!]!
  }
}
```

不存在 `Mutation` 或 `Subscription` 型別——GraphQL API 為只讀分析查詢。

***

## Chain Group

按目標區塊鏈生態，Cube 分為三組：

| Chain Group | `network` 引數 | 可用網路                  | 說明                                         |
| :---------- | :----------- | :-------------------- | :----------------------------------------- |
| **EVM**     | 必填           | `eth`、`bsc`、`polygon` | 所有 EVM 相容鏈共用的 Cube                         |
| **Solana**  | 不需要          | `sol`（隱式）             | Solana 專用 Cube（含 Instructions、DEXOrders 等） |
| **Trading** | 不需要          | 跨鏈（`sol`、`eth`、`bsc`） | 預聚合交易分析（OHLC K 線、代幣統計等），資料中帶 `chain` 維度    |

<Note>
  **EVM** 組必須傳入 `network` 以選擇鏈。**Solana** 與 **Trading** 不需要 `network`——Solana 為隱式，Trading 在資料內透過 `chain` 維度區分。
</Note>

完整劃分見 [Chain Groups](/zh-Hant/graphql/schema/chain-groups)。

***

## Chain Group 引數

每個 Chain Group 接受兩個可選引數，用於控制資料來源行為：

### Dataset

`dataset` 控制查詢資料的時間範圍：

| 值          | 說明                            |
| :--------- | :---------------------------- |
| `combined` | 全量範圍——同時包含近期與歷史資料\*\*（預設）\*\* |
| `realtime` | 僅近期資料（約最近 24 小時）              |
| `archive`  | 歷史資料，上限為保留 TTL                |

```graphql theme={null}
query {
  Solana(dataset: realtime) {
    DEXTrades(limit: {count: 10}, orderBy: {descending: Block_Time}) {
      Block { Time }
      Trade { Buy { Amount } }
    }
  }
}
```

### Aggregates

`aggregates` 控制是否使用預聚合（DWM/DWS）表：

| 值      | 說明                                  |
| :----- | :---------------------------------- |
| `yes`  | 在可用時優先使用預聚合表\*\*（適用 Cube 的預設行為）\*\* |
| `no`   | 僅使用原始明細表                            |
| `only` | 僅使用預聚合表（更快但欄位受限）                    |

```graphql theme={null}
query {
  Trading(aggregates: only) {
    Pairs(
      where: { Token: { Address: { is: "0x..." } } }
      limit: {count: 100}
    ) {
      Interval { Time }
      Price { Ohlc { Open High Low Close } }
      Volume { Usd }
    }
  }
}
```

<Tip>
  詳細用法、支援的表與效能建議見 [Dataset & Aggregates](/zh-Hant/graphql/schema/dataset-aggregates)。
</Tip>

***

## 通用引數模式

在 Chain Group 內，每個 Cube 欄位接受同一套標準引數，外加可選的 Cube 專屬 **selector**：

| 引數          | 型別              | 必填 | 說明                                  |
| :---------- | :-------------- | :- | :---------------------------------- |
| `where`     | `{Cube}Filter`  | 否  | 與維度層級一致的巢狀篩選物件                      |
| `limit`     | `LimitInput`    | 否  | 分頁：`{count: Int, offset: Int}`      |
| `orderBy`   | `{Cube}OrderBy` | 否  | 排序列舉（`{Path}_ASC` / `{Path}_DESC`）  |
| *selectors* | 篩選輸入            | 否  | 快捷篩選（如 `tokenAddress: {is: "..."}`） |

```graphql theme={null}
query {
  Solana {
    DEXTrades(
      tokenAddress: {is: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"}
      where: { Block: { Time: { after: "2026-01-01T00:00:00Z" } } }
      limit: { count: 50, offset: 0 }
      orderBy: {descending: Block_Time}
    ) {
      Block { Time }
      Trade { Buy { Amount PriceInUSD } }
    }
  }
}
```

### LimitInput

```graphql theme={null}
input LimitInput {
  count: Int   # Number of rows to return
  offset: Int  # Number of rows to skip (for pagination)
}
```

預設 `count` 因 Cube 而異（多為 25）。多數 Cube 最大為 10,000。

***

## 每個 Cube 的生成型別

對每個 Cube，activecube-rs 會生成三類配套型別：

<CardGroup cols={3}>
  <Card title="Record 型別" icon="table">
    `{Cube}Record` — 返回值型別，包含全部可選維度與指標。欄位結構與 Cube 維度層級一致。
  </Card>

  <Card title="Filter 輸入" icon="filter">
    `{Cube}Filter` — 巢狀輸入物件，各維度對映到篩選原語（`StringFilter`、`IntFilter`、`DateTimeFilter` 等）。
  </Card>

  <Card title="OrderBy 列舉" icon="arrow-down-a-z">
    `{Cube}OrderBy` — 每條維度路徑在升序與降序下的列舉變體（如 `Block_Time_ASC`、`Trade_Buy_Amount_DESC`）。
  </Card>
</CardGroup>

**DEXTrades 示例：**

```graphql theme={null}
# Record type (return shape)
type DEXTradesRecord {
  Block: DEXTradesBlockRecord
  Transaction: DEXTradesTransactionRecord
  Trade: DEXTradesTradeRecord
  Pool: DEXTradesPoolRecord
  IsSuspect: Boolean
  count: Int
  sum(of: DEXTradesSumOf!): Float
}

# Filter input
input DEXTradesFilter {
  Block: DEXTradesBlockFilter
  Transaction: DEXTradesTransactionFilter
  Trade: DEXTradesTradeFilter
  Pool: DEXTradesPoolFilter
  IsSuspect: BoolFilter
  any: [DEXTradesFilter!]  # OR logic
}

# OrderBy enum (partial)
enum DEXTradesOrderBy {
  Block_Time_ASC
  Block_Time_DESC
  Trade_Buy_Amount_ASC
  Trade_Buy_Amount_DESC
  # ...
}
```

***

## Introspection

Schema 支援標準 GraphQL introspection。可用 `__schema`、`__type` 查詢探索型別、欄位與引數：

<Tabs>
  <Tab title="列出所有 Cube">
    ```graphql theme={null}
    query {
      __schema {
        queryType {
          fields {
            name
            description
            args { name type { name } }
          }
        }
      }
    }
    ```
  </Tab>

  <Tab title="檢視某 Cube 型別">
    ```graphql theme={null}
    query {
      __type(name: "DEXTradesRecord") {
        name
        fields {
          name
          type { name kind ofType { name } }
        }
      }
    }
    ```
  </Tab>

  <Tab title="列出篩選運算子">
    ```graphql theme={null}
    query {
      __type(name: "StringFilter") {
        name
        inputFields {
          name
          type { name kind }
        }
      }
    }
    ```
  </Tab>
</Tabs>

<Tip>
  [GraphQL IDE](https://ide.chainstream.io) 會自動拉取 introspection schema 以驅動自動補全與內聯文件。可在介面中互動探索完整 schema，無需手寫 introspection 查詢。
</Tip>

***

## 下一步

<CardGroup cols={2}>
  <Card title="資料 Cube" icon="cubes" href="/zh-Hant/graphql/schema/cubes">
    瀏覽全部 25 個 Cube——欄位、selector 與數倉分層。
  </Card>

  <Card title="Chain Group" icon="layer-group" href="/zh-Hant/graphql/schema/chain-groups">
    瞭解 EVM、Solana、Trading 三個 Chain Group 及其可用 Cube。
  </Card>

  <Card title="Dataset 與 Aggregates" icon="database" href="/zh-Hant/graphql/schema/dataset-aggregates">
    使用 `dataset` 與 `aggregates` 控制資料來源範圍與預聚合行為。
  </Card>

  <Card title="篩選" icon="filter" href="/zh-Hant/graphql/schema/filtering">
    學習如何用 `where` 與 selector 快捷方式收窄查詢。
  </Card>

  <Card title="排序與分頁" icon="arrow-down-1-9" href="/zh-Hant/graphql/schema/ordering-pagination">
    使用 `orderBy` 與 `limit` 對大資料集排序與分頁。
  </Card>

  <Card title="指標與聚合" icon="chart-simple" href="/zh-Hant/graphql/schema/metrics-aggregation">
    在查詢中使用 `count`、`sum`、`avg`、`min`、`max`、`uniq` 聚合資料。
  </Card>
</CardGroup>
