如何设计表结构支持动态新增语言?是否应使用 JSON 字段或单独的翻译表?

解读

国内业务出海、多语言运营已成标配,面试官想确认两点:

  1. 你是否理解“动态新增语言”带来的运维、性能、数据一致性挑战;
  2. 在 NestJS + TypeORM/Prisma 技术栈里,你能否给出可落地的 DDL、实体定义、仓储模式与迁移方案,而不是空谈理论。
    回答时必须兼顾:
  • 运营侧:市场同学随时要上新语言,不能发版;
  • 研发侧:类型安全、查询性能、索引、分页、聚合、全文检索;
  • DBA 侧:DDL 轻量、备份恢复、主从同步、云数据库规格限制;
  • 合规侧:国内数据不出境,海外语言数据可放海外节点。

知识点

  1. 关系模型三范式 vs 半结构化 JSON 的权衡;
  2. MySQL8 / PostgreSQL JSONB 的函数索引、部分索引、生成列;
  3. NestJS 中 TypeORM 的 @AfterLoad、@BeforeInsert 生命周期,Prisma 的 Json 类型与动态 select;
  4. 翻译表的 EAV(Entity-Attribute-Value)陷阱与“单列多行”最佳实践;
  5. 读写分离场景下,翻译字段的 JOIN 与覆盖索引优化;
  6. 缓存:i18n key → Map 的 LRU 本地缓存 + Redis 分布式缓存;
  7. 迁移策略:pt-online-schema-change、gh-ost、PostgreSQL pg_repack;
  8. 类型安全:如何给动态语言代码生成 TypeScript 类型声明(ts-node + codegen)。

答案

“没有银弹,先给标准方案,再讲灰度与回滚。”

一、标准方案:独立翻译表(MySQL 示例)

  1. DDL
    CREATE TABLE product (
    id BIGINT PRIMARY KEY AUTO_INCREMENT,
    sku VARCHAR(32) NOT NULL UNIQUE,
    price DECIMAL(10,2) NOT NULL,
    status TINYINT NOT NULL DEFAULT 1,
    created_at DATETIME(3) DEFAULT CURRENT_TIMESTAMP(3),
    updated_at DATETIME(3) DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3)
    );

    CREATE TABLE product_i18n (
    id BIGINT PRIMARY KEY AUTO_INCREMENT,
    product_id BIGINT NOT NULL,
    lang CHAR(5) NOT NULL, -- en-US, zh-CN,utf8mb4 节省空间
    field VARCHAR(30) NOT NULL, -- name, desc, spec
    content TEXT NOT NULL,
    created_at DATETIME(3) DEFAULT CURRENT_TIMESTAMP(3),
    updated_at DATETIME(3) DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3),
    UNIQUE KEY uk_product_lang_field (product_id, lang, field),
    KEY idx_lang_field (lang, field)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

  2. NestJS 实体(TypeORM)
    @Entity()
    export class Product {
    @PrimaryGeneratedColumn() id: number;
    @Column() sku: string;
    @Column('decimal', { precision: 10, scale: 2 }) price: number;
    @OneToMany(() => ProductI18n, i18n => i18n.product, { cascade: true })
    i18ns: ProductI18n[];
    }

    @Entity()
    @Unique(['product', 'lang', 'field'])
    export class ProductI18n {
    @PrimaryGeneratedColumn() id: number;
    @ManyToOne(() => Product, p => p.i18ns, { onDelete: 'CASCADE' })
    product: Product;
    @Column({ length: 5 }) lang: string;
    @Column({ length: 30 }) field: string;
    @Column('text') content: string;
    }

  3. Repository 模式,支持批量回写
    class ProductRepository {
    async saveWithI18n(dto: CreateProductDto, langMap: Record<string, any>) {
    const product = await this.prodRepo.save(dto);
    const i18nEntities = Object.entries(langMap).flatMap(([lang, fields]) =>
    Object.entries(fields).map(([field, content]) =>
    this.i18nRepo.create({ product, lang, field, content })
    )
    );
    await this.i18nRepo.insert(i18nEntities);
    return product;
    }

    async findBySku(sku: string, lang: string) {
    return this.prodRepo
    .createQueryBuilder('p')
    .leftJoinAndSelect('p.i18ns', 'i', 'i.lang = :lang', { lang })
    .where('p.sku = :sku', { sku })
    .getOne();
    }
    }

  4. 动态新增语言
    市场同学只需在后台插入一条 product_i18n 记录即可,无需发版;
    若需要默认回退,可在 Service 层做 “lang → fallback → en-US” 三级链。

二、JSON 字段方案(PostgreSQL JSONB 示例)

  1. DDL
    CREATE TABLE product (
    id BIGSERIAL PRIMARY KEY,
    sku VARCHAR(32) UNIQUE NOT NULL,
    price NUMERIC(10,2) NOT NULL,
    i18n JSONB NOT NULL DEFAULT '{}',
    created_at TIMESTAMPTZ DEFAULT NOW(),
    updated_at TIMESTAMPTZ DEFAULT NOW()
    );
    CREATE INDEX idx_i18n_gin ON product USING GIN (i18n);
    CREATE INDEX idx_i18n_lang_name ON product ((i18n ->> 'zh-CN:name')); -- 部分索引示例

  2. NestJS 实体(Prisma)
    model Product {
    id BigInt @id @default(autoincrement())
    sku String @unique
    price Decimal
    i18n Json
    createdAt DateTime @default(now())
    updatedAt DateTime @updatedAt
    }

  3. 查询
    const list = await this.prisma.product.findMany({
    where: {
    i18n: {
    path: ['zh-CN', 'name'],
    string_contains: '手机'
    }
    }
    });

三、何时选谁

  • 翻译字段 <5 个、需要频繁模糊搜索、聚合、排序 → 独立表;
  • 翻译字段多且嵌套、结构灵活、查询简单 → JSONB;
  • MySQL5.7 以下无 JSONB,直接放弃 JSON 方案;
  • 需要全文检索 → PostgreSQL JSONB + GIN + pgroonga 或独立表 + Elasticsearch。

四、灰度与回滚

  1. 双写:新语言同时写旧字段与翻译表,七天后再切流量;
  2. 使用 pt-online-schema-change 给 product_i18n 加字段,零锁表;
  3. 若 JSON 方案性能退化,可在线创建生成列并建索引,无需停机。

拓展思考

  1. 百亿级数据:把 product_i18n 按 lang 做水平分表,再按 product_id 分片,用 ShardingSphere-Proxy;
  2. 边缘节点:海外 CDN 节点只读,翻译表通过 Canal 同步到海外只读实例,降低延迟;
  3. 类型安全:写一个小脚本,每晚拉取 product_i18n 的 lang 列表,自动生成 src/i18n/types/product.d.ts,保证前端与后端同时校验;
  4. Serverless 场景:AWS Aurora Serverless v2 不支持 JSONB 函数索引,需改回独立表;
  5. 合规:欧盟市场要求被遗忘权,删除 product 时同步物理删除 product_i18n,避免 JSONB 字段残留敏感词。