MikroORM7.2 中文文档
Schema 与数据库/物化视图
已译 96/96

物化视图

物化视图会把查询结果物理存储下来,以牺牲数据新鲜度为代价提供更快的读取性能。与常规视图不同,物化视图必须显式刷新,才能反映底层数据的变化。

定义物化视图实体

要创建物化视图实体,请在实体选项中使用 view: { materialized: true }:

./entities/AuthorStats.ts
import { defineEntity, p } from '@mikro-orm/postgresql';

const AuthorStatsSchema = defineEntity({
  name: 'AuthorStats',
  tableName: 'author_stats_matview',
  view: { materialized: true },
  expression: `
    select
      a.id,
      a.name,
      count(b.id)::int as book_count
    from author a
    left join book b on b.author_id = a.id
    group by a.id
  `,
  properties: {
    id: p.integer().primary(),
    name: p.string(),
    bookCount: p.integer(),
  },
});

export class AuthorStats extends AuthorStatsSchema.class {}
AuthorStatsSchema.setClass(AuthorStats);
./entities/AuthorStats.ts
import { defineEntity, p } from '@mikro-orm/postgresql';

export const AuthorStats = defineEntity({
  name: 'AuthorStats',
  tableName: 'author_stats_matview',
  view: { materialized: true },
  expression: `
    select
      a.id,
      a.name,
      count(b.id)::int as book_count
    from author a
    left join book b on b.author_id = a.id
    group by a.id
  `,
  properties: {
    id: p.integer().primary(),
    name: p.string(),
    bookCount: p.integer(),
  },
});
./entities/AuthorStats.ts
import { Entity, Property, PrimaryKey } from '@mikro-orm/decorators/legacy';

@Entity({
  tableName: 'author_stats_matview',
  view: { materialized: true },
  expression: `
    select
      a.id,
      a.name,
      count(b.id)::int as book_count
    from author a
    left join book b on b.author_id = a.id
    group by a.id
  `,
})
export class AuthorStats {

  @PrimaryKey()
  id!: number;

  @Property()
  name!: string;

  @Property()
  bookCount!: number;

}
./entities/AuthorStats.ts
import { Entity, Property, PrimaryKey } from '@mikro-orm/decorators/legacy';

@Entity({
  tableName: 'author_stats_matview',
  view: { materialized: true },
  expression: `
    select
      a.id,
      a.name,
      count(b.id)::int as book_count
    from author a
    left join book b on b.author_id = a.id
    group by a.id
  `,
})
export class AuthorStats {

  @PrimaryKey()
  id!: number;

  @Property()
  name!: string;

  @Property()
  bookCount!: number;

}

创建不带数据的物化视图

默认情况下,物化视图在创建时会立即填充数据(WITH DATA)。如果你想创建一个稍后再填充的空物化视图,请设置 withData: false:

const AuthorStats = defineEntity({
  name: 'AuthorStats',
  tableName: 'author_stats_matview',
  view: { materialized: true, withData: false }, // 以 "WITH NO DATA" 创建
  expression: `select ...`,
  properties: { ... },
});

当底层表在 schema 创建期间为空,或者你想精确控制首次数据填充的时机时,这很有用。

刷新物化视图

由于物化视图会缓存查询结果,你需要刷新它们才能看到更新后的数据。请使用 PostgreSqlEntityManager 上的 refreshMaterializedView 方法:

import { MikroORM, EntityManager } from '@mikro-orm/postgresql';

const orm = await MikroORM.init({ ... });
const em = orm.em;

// 刷新物化视图
await em.refreshMaterializedView(AuthorStats);

// 现在查询会返回更新后的数据
const stats = await em.find(AuthorStats, {});

并发刷新

PostgreSQL 支持并发刷新物化视图,这允许在刷新期间继续读取。这要求物化视图上有唯一索引:

// 并发刷新(要求视图上有唯一索引)
await em.refreshMaterializedView(AuthorStats, { concurrently: true });

注意: 并发刷新要求物化视图上至少有一个唯一索引。没有它,PostgreSQL 会抛出错误。

查询物化视图

物化视图的查询方式与其他任何实体一样:

// 查找全部
const allStats = await em.find(AuthorStats, {});

// 带条件查找
const prolificAuthors = await em.find(AuthorStats, {
  bookCount: { $gte: 5 },
});

// 查找单个
const authorStats = await em.findOne(AuthorStats, { name: 'Jon Snow' });

只读行为

物化视图实体会被自动标记为只读(readonly: true)。尝试持久化对物化视图实体的修改会导致错误:

const stats = await em.findOne(AuthorStats, { id: 1 });
stats.bookCount = 100; // 该修改不会被持久化
await em.flush(); // 不会为该实体生成 UPDATE

Schema 生成

schema 生成器会自动处理物化视图:

// 创建 schema(包含 CREATE MATERIALIZED VIEW 语句)
await orm.schema.create();

// 删除 schema(包含 DROP MATERIALIZED VIEW 语句)
await orm.schema.drop();

// 更新 schema(检测物化视图的变更)
await orm.schema.update();

生成的 SQL

创建物化视图会生成:

create materialized view "author_stats_matview" as
  select a.id, a.name, count(b.id)::int as book_count
  from author a
  left join book b on b.author_id = a.id
  group by a.id
with data;

使用 withData: false 时:

create materialized view "author_stats_matview" as
  select ...
with no data;

限制

  • 仅 PostgreSQL: 物化视图只在 PostgreSQL 上受支持。如果你尝试在其他数据库上使用 view: { materialized: true },它们会抛出错误。
  • 不会自动刷新: MikroORM 不会自动刷新物化视图。你必须手动调用 refreshMaterializedView(),或搭建数据库层面的刷新机制(触发器、定时任务等)。

最佳实践

  1. 选择合适的刷新策略: 对于频繁变化的数据,请考虑改用常规视图。把物化视图用于变化不频繁、或可以接受陈旧数据的场景。

  2. 添加索引: 物化视图支持索引。为你经常查询的列添加索引:

    CREATE UNIQUE INDEX author_stats_id_idx ON author_stats_matview (id);
    CREATE INDEX author_stats_book_count_idx ON author_stats_matview (book_count);
  3. 安排刷新计划: 使用数据库调度器(pg_cron)或应用层调度,在低流量时段刷新物化视图。

  4. 在生产环境中使用并发刷新: 如果你的应用需要在刷新期间读取视图,请始终使用 { concurrently: true }(要求有唯一索引)。

  5. 监控视图大小: 物化视图会占用磁盘空间。请监控它们的大小,并针对大数据集考虑分区策略。