---
title: 流式查询
---

来源：https://mikro-orm.io/docs/streaming

如果你想处理大量实体而不必一次性把它们全部载入内存，可以使用 `em.stream()` 方法。它返回一个异步可迭代对象，因此你可以在 `for await ... of` 循环中使用它。

```ts
const stream = em.stream(Book, {
  populate: ['author'],
  where: { price: { $gt: 100 } },
  orderBy: { id: 'ASC' },
});

for await (const book of stream) {
  console.log(book.title);
  console.log(book.author.name);
}
```

使用流式查询时有几项约束：

- 返回的实体不受管理。标识性只在返回的实体图内部成立。
- 所有被填充的关联都强制使用 joined 策略。
- 填充 to-many 关联时，只会返回完全水合的实体。
- 你应该提供 `orderBy` 子句以确保顺序一致。
- 使用 mongodb 驱动时，只能流式获取根实体，`populate` 选项会被忽略。

<a id="chunk-size"></a>
## 块大小

ORM 会分批从数据库获取行；`chunkSize` 选项控制每次往返取回多少行。较小的值能降低内存占用但代价是更多次往返；较大的值则相反。无论该值是多少，异步迭代器始终一次产出一个实体。

```ts
const stream = em.stream(Book, {
  orderBy: { id: 'ASC' },
  chunkSize: 100, // 100 是默认值
});
```

该选项在 PostgreSQL、MSSQL、Oracle 与 MongoDB 上生效。在 MySQL、MariaDB、SQLite 与 libSQL 上，底层驱动始终逐行流式返回、没有批大小调节项，因此该选项在那里不起作用。

<a id="streaming-row-by-row"></a>
## 逐行流式返回

填充 to-many 关联时，ORM 会流式产出完全合并的实体，而不是产出每一行。你可以通过指定 `mergeResults: false` 退出这一行为。这会产出 SQL 结果中的每一行，但仍会映射为实体——这意味着 to-many 集合最多只包含一项，并且当根实体在被填充的集合中有多项时，你会得到重复的根实体。

```ts
const stream = em.stream(Book, {
  populate: ['author'],
  where: { price: { $gt: 100 } },
  orderBy: { id: 'ASC' },
  mergeResults: false,
});
```

<a id="streaming-raw-results"></a>
## 流式获取原始结果

要流式获取原始结果而非实体，可以使用 `QueryBuilder` 配合 `mapResults: true` 选项：

```ts
const stream = em.createQueryBuilder(Author, 'a')
  .leftJoinAndSelect('books', 'b')
  .orderBy({ id: 'desc', books: { title: 'asc' } })
  .stream({ mapResults: true });
```

这会禁用到实体的映射，改为返回 POJO，但仍会把列名转换为实体属性名。

或者，你可以使用 `rawResults: true` 来流式获取不做任何映射的原始值：

```ts
const stream = em.createQueryBuilder(Author, 'a')
  .leftJoinAndSelect('books', 'b')
  .orderBy({ id: 'desc', books: { title: 'asc' } })
  .stream({ rawResults: true });
```

<a id="virtual-entities"></a>
## 虚拟实体

流式查询对虚拟实体同样有效，`expression` 既可以是 `QueryBuilder`，也可以是原始 SQL 查询：

```ts
const BookWithAuthor = defineEntity({
  name: 'BookWithAuthor',
  expression: (em: EntityManager) => {
    return em.createQueryBuilder(Book, 'b')
      .select([sql`min(b.title)`.as('title'), sql`min(a.name)`.as('author_name')])
      .join('b.author', 'a')
      .groupBy('b.id');
  },
  // 或 `expression: 'select min(b.title) as title, min(a.name) as author_name from books...'`
  properties: {
    title: p.string(),
    authorName: p.string(),
  },
});

const stream = em.stream(BookWithAuthor);
```

<a id="mongodb-limitations"></a>
## MongoDB 的限制

使用 MongoDB 驱动时，只能流式获取根实体。`populate` 选项会被忽略，不会填充任何关联。如果你需要访问关联，请在流式结果上显式使用 `em.populate`。注意，之后你应该清空 EntityManager，或者使用一个临时的 fork。

```ts
const stream = em.stream(Book, {
  where: { price: { $gt: 100 } },
  orderBy: { id: 'ASC' },
});

for await (const book of stream) {
  console.log(book.title);
  const fork = em.fork();
  await fork.populate(book, ['author']);
  console.log(book.author.name);
}
```

对于由聚合管道支撑的虚拟实体，你同样可以流式获取，但你的 `expression` 需要返回一个流。为此你可以使用 `em.streamAggregate()` 方法（与之相对，`em.aggregate()` 会直接返回全部结果）。为了能有单一虚拟实体定义同时适用于 `em.find` 与 `em.stream`，请使用 `expression` 回调的第 4 个参数来检测是否请求了流式返回：

```ts
const BookWithAuthor = defineEntity({
  name: 'BookWithAuthor',
  expression: (em: EntityManager, where, options, stream) => {
    const pipeline = [
      { $match: { /* ... */ } },
      { $lookup: { /* ... */ } },
      // ...
    ];

    if (stream) {
      return em.streamAggregate(Book, pipeline);
    }

    return em.aggregate(Book, pipeline);
  },
  properties: {
    title: p.string(),
    authorName: p.string(),
  },
});
```
