# Split In Batches

> 将数组拆分为单个条目或批次，以便并行或迭代处理。

Source: https://docs.sommatic.ai/zh/nodes/flow.split/

- 标识: `flow.split`
- 类别: 流程控制
- 版本: 1.0.0
- 状态: 可用
- 执行方式: sync

将数组拆分为单个条目或批次，以便并行或迭代处理。

该算子用于遍历输入载荷中的条目列表。每个条目（或每批条目）都会触发“loop”输出端口；所有条目处理完毕后，触发“done”端口。

**行为：**
- **迭代：** 为数组中的每个条目或批次发出一条消息。
- **上下文保留：** 子执行继承父级上下文。
- **分批：** 可将条目分组为批次（例如每批 10 个）以提升效率。

**适用场景：**
- 处理来自 CSV 的新用户列表。
- 向某一订阅者细分群体发送邮件。
- 逐条处理订单明细行。

## 配置

- `path` (string, 可选, 支持表达式): 指向输入载荷中数组的 JSONata 路径（例如 `data.items`）。留空时，根载荷本身被视为数组。
- `batch_size` (integer, 可选): 每个发出批次中包含的条目数。 默认值: `1`.

配置中会显示通用执行设置，但该节点目前不执行重试（`retryOnFail`、`maxTries`）。所有节点均未实现 `continueOnFail`。

## 输出端口

- `out` (默认): 为数组中的每个条目或批次触发。
- `done`: 所有条目处理完毕后激活。
- `error`: 输入不是有效数组时激活。

## 输入契约

- `payload` (object, 可选)

## 输出契约

- `payload` (array<object>, 可选): 该批条目。

## 在表达式中

后续节点可通过 `$("Split In Batches").item.json.<路径>` 读取此节点输出中的内容（请把 `Split In Batches` 换成你的节点标签）。**Editor** 标记工作流编辑器在 Previous Nodes 中提示的路径（输出契约）；**Worker** 标记 worker 实际通过 `out` 返回的路径，依据“端口”一节所示的输出。

- `$("Split In Batches").item.json.payload` (array): 该批条目。 **worker 不返回：读取结果为 undefined.**
- `$("Split In Batches").item.json.order_id` (string) = `"ord_1"` (编辑器不提示)
- `$("Split In Batches").item.json.total` (number) = `10` (编辑器不提示)


## 工作原理

展开数组：引擎对每个元素（或批次）执行一次连接到 `out` 的节点，然后通过 `done` 发出元素数量。

1. 解析 `path`。返回数组或对象的 `{{ }}`（`{{ $json.items }}`）直接使用；纯文本作为 JSONata 针对 payload 求值（`data.items`）；`path` 为空时使用整个 payload。
2. 将数字键对象（`{ "0": {...}, "1": {...} }`）按键顺序还原为数组；空对象变为 `[]`。
3. 值不是数组时失败。
4. 空数组直接以 `{}` 从 `done` 输出，`out` 不输出任何内容。
5. 否则返回数组并带 `meta.split` 与 `meta.batch_size`。引擎会把每个连接到 `out` 的节点按元素（`batch_size` 为 1）或按每 `batch_size` 个元素的切片排入队列，各自以该元素或切片作为 payload。
6. 随后将连接到 `done` 的节点排入队列，payload 为 `{ total_items }`（元素数量）。

## 在工作流中

### 节点

```json
{
  "node_id": "node-each-order",
  "label": "Each order",
  "operator_slug": "flow.split",
  "operator_version": "1.0.0",
  "config": {
    "path": "{{ $json.orders }}",
    "batch_size": 1
  }
}
```

### Envelope

```json
{
  "ok": true,
  "data": [
    {
      "order_id": "ord_1",
      "total": 10
    },
    {
      "order_id": "ord_2",
      "total": 25
    },
    {
      "order_id": "ord_3",
      "total": 7
    }
  ],
  "meta": {
    "split": true,
    "batch_size": 1
  },
  "port": "out"
}
```

## 输出端口 (代码中的行为)

### `out`

每个元素触发一次（`batch_size` > 1 时为批次数组）。payload 就是该元素本身。

```json
{
  "order_id": "ord_1",
  "total": 10
}
```

### `done`

所有元素排队之后。空数组时 payload 为 `{}`。

```json
{
  "total_items": 3
}
```

### `error`

`path` 处的值不是数组，或 JSONata 出错。

```json
{
  "ok": false,
  "errors": [
    "Target at path 'data.items' is not an array. Got: object. Keys found: [id, name]"
  ],
  "port": "error"
}
```

## 代码中的行为

- `batch_size`: 大于 1 时每个 `out` payload 是数组切片，但 `done` 报告的仍是元素数量，因此下游的 `flow.join` 永远不会触发。

## 错误

| 消息 | 端口 | 原因与处理 |
| --- | --- | --- |
| `Target at path '<path\|root>' is not an array. Got: <type>. Keys found: [<keys>]` | `error` | `path` 指向对象、字符串或不存在。请对照实际 payload 检查路径。 |
| `<JSONata message>` | `error` | `path` 中的 JSONata 无效；消息位于 `data.error`。 |

## 说明与限制

- 每次节点执行都计入引擎每次运行 100 步的上限；超过后运行失败并报 `Max step ceiling reached (100)`。各项按队列顺序依次处理，并非并行。
- `done` 在各元素到达其第一个节点后立即入队，因此 `done` 上的节点可能在元素分支结束前就执行。只有 `flow.join` 会等待所有元素。
- 当返回的信封没有 `data`（或 `data` 为假值）时，引擎会把整个信封作为节点输出：经 `error` 端口时，下一个节点收到的 payload 是 `{ ok: false, errors: [...], port: "error" }`。


## 契约（JSON Schema）

### All (`*.definition.js`)

```json
{
  "slug": "flow.split",
  "name": "Split In Batches",
  "category": "flow",
  "version": "1.0.0",
  "description": "Splits an array into individual items or batches for parallel or iterative processing.\n\n  This operator allows you to iterate over a list of items found in the input payload. For each item (or batch of items), it triggers the 'loop' output port. Once all items have been processed, it triggers the 'done' port.\n\n  **Behavior:**\n  - **Iteration:** Emits a message for each item/batch in the array.\n  - **Context Preservation:** Child executions inherit the parent context.\n  - **Batching:** Can group items into batches (e.g., size 10) for efficiency.\n\n  **Use Cases:**\n  - Processing a list of new users from a CSV.\n  - Sending emails to a segment of subscribers.\n  - Processing order line items individually.",
  "capabilities": [
    "loop",
    "iteration",
    "array",
    "fan-out"
  ],
  "config_schema": {
    "type": "object",
    "properties": {
      "path": {
        "type": "string",
        "title": "Array Input Path",
        "description": "JSONata path to the array in the input payload (e.g. `data.items`). If empty, the root payload is treated as the array.",
        "format": "expression"
      },
      "batch_size": {
        "type": "integer",
        "title": "Batch Size",
        "default": 1,
        "minimum": 1,
        "description": "Number of items to include in each emitted batch."
      },
      "execution": {
        "type": "object",
        "title": "Execution Settings",
        "properties": {
          "alwaysOutputData": {
            "type": "boolean",
            "title": "Always Output Data",
            "description": "Always output data, even on error (if configured).",
            "default": false
          },
          "retryOnFail": {
            "type": "boolean",
            "title": "Retry On Fail",
            "description": "Retry the execution if it fails.",
            "default": false
          },
          "maxTries": {
            "type": "integer",
            "title": "Max Retries",
            "description": "Number of retries.",
            "default": 3,
            "displayOptions": {
              "show": {
                "retryOnFail": [
                  true
                ]
              }
            }
          },
          "waitBetweenTries": {
            "type": "integer",
            "title": "Wait Between Retries (ms)",
            "default": 1000,
            "displayOptions": {
              "show": {
                "retryOnFail": [
                  true
                ]
              }
            }
          },
          "continueOnFail": {
            "type": "boolean",
            "title": "Continue On Fail",
            "description": "Do not crash workflow on error.",
            "default": false
          },
          "timeout_ms": {
            "type": "integer",
            "title": "Timeout (ms)",
            "description": "Max execution time for this node before it is killed, in milliseconds. Honored by long-running operators (e.g. OCR/extraction, inline code). Default 300000 (5 min).",
            "default": 300000
          }
        }
      }
    }
  },
  "input_contract_schema": {
    "type": "object",
    "description": "Payload containing the array to split.",
    "properties": {
      "payload": {
        "type": "object"
      }
    }
  },
  "output_contract_schema": {
    "type": "object",
    "description": "A single item or a batch of items from the source array.",
    "properties": {
      "payload": {
        "type": "array",
        "items": {
          "type": "object"
        },
        "description": "The batch of items."
      }
    }
  },
  "ports": [
    {
      "port_id": "out",
      "label": "Loop Item",
      "is_default": true,
      "description": "Emits for each item or batch in the array."
    },
    {
      "port_id": "done",
      "label": "Done",
      "description": "Activated when all items have been processed."
    },
    {
      "port_id": "error",
      "label": "Error",
      "description": "Activated if the input is not a valid array."
    }
  ],
  "execution_mode": "sync",
  "tags": [
    "loop",
    "iterator",
    "fan-out",
    "batch"
  ],
  "is_stateful": true,
  "publisher": {
    "identity": "org_sommatic_ai",
    "profile": {
      "name": "Sommatic AI",
      "verified": true,
      "url": "https://me.veripass.com/sommatic",
      "logo_url": null
    }
  }
}
```

### config_schema

```json
{
  "type": "object",
  "properties": {
    "path": {
      "type": "string",
      "title": "Array Input Path",
      "description": "JSONata path to the array in the input payload (e.g. `data.items`). If empty, the root payload is treated as the array.",
      "format": "expression"
    },
    "batch_size": {
      "type": "integer",
      "title": "Batch Size",
      "default": 1,
      "minimum": 1,
      "description": "Number of items to include in each emitted batch."
    },
    "execution": {
      "type": "object",
      "title": "Execution Settings",
      "properties": {
        "alwaysOutputData": {
          "type": "boolean",
          "title": "Always Output Data",
          "description": "Always output data, even on error (if configured).",
          "default": false
        },
        "retryOnFail": {
          "type": "boolean",
          "title": "Retry On Fail",
          "description": "Retry the execution if it fails.",
          "default": false
        },
        "maxTries": {
          "type": "integer",
          "title": "Max Retries",
          "description": "Number of retries.",
          "default": 3,
          "displayOptions": {
            "show": {
              "retryOnFail": [
                true
              ]
            }
          }
        },
        "waitBetweenTries": {
          "type": "integer",
          "title": "Wait Between Retries (ms)",
          "default": 1000,
          "displayOptions": {
            "show": {
              "retryOnFail": [
                true
              ]
            }
          }
        },
        "continueOnFail": {
          "type": "boolean",
          "title": "Continue On Fail",
          "description": "Do not crash workflow on error.",
          "default": false
        },
        "timeout_ms": {
          "type": "integer",
          "title": "Timeout (ms)",
          "description": "Max execution time for this node before it is killed, in milliseconds. Honored by long-running operators (e.g. OCR/extraction, inline code). Default 300000 (5 min).",
          "default": 300000
        }
      }
    }
  }
}
```

### input_contract_schema

```json
{
  "type": "object",
  "description": "Payload containing the array to split.",
  "properties": {
    "payload": {
      "type": "object"
    }
  }
}
```

### output_contract_schema

```json
{
  "type": "object",
  "description": "A single item or a batch of items from the source array.",
  "properties": {
    "payload": {
      "type": "array",
      "items": {
        "type": "object"
      },
      "description": "The batch of items."
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "out",
    "label": "Loop Item",
    "is_default": true,
    "description": "Emits for each item or batch in the array."
  },
  {
    "port_id": "done",
    "label": "Done",
    "description": "Activated when all items have been processed."
  },
  {
    "port_id": "error",
    "label": "Error",
    "description": "Activated if the input is not a valid array."
  }
]
```
