如何为 DBIC 结果集添加 PostgreSQL GIN 索引下推?

解读

在国内互联网或金融公司面试中,这道题常被用来区分“只会写 CRUD”与“能驾驭海量数据”的候选人。
DBIC(DBIx::Class)默认把过滤条件翻译成 SQL WHERE,但 PostgreSQL 的 GIN 索引(倒排、jsonb、数组、全文检索)只有在查询计划里出现“Index Scan”才算真正“下推”。
如果写法不当,DBIC 会生成 WHERE col LIKE '%xxx%' 或 WHERE to_tsvector('config', col) = plainto_tsquery('xxx'),导致 GIN 索引失效,退化成全表扫描。
因此,题目真正考察的是:

  1. 让 DBIC 生成 PostgreSQL 能识别并走 GIN 的运算符(@@、@>、&&、jsonb_path_ops 等)。
  2. 保证查询参数侧不出现函数或隐式类型转换,避免“索引不可见”。
  3. 在 ResultSet 链式调用里把上述逻辑封装成可复用的组件,而不是裸写 SQL 字符串。

知识点

  1. DBIC 相关
    • ResultSource 的 sqlt_deploy_hook 钩子,可下发原生 DDL 创建 GIN。
    • ResultSet 的 search() 支持 { -ident => … }、{ -value => … } 以及 literal SQL 片段。
    • 自定义 ResultSetComponent,用 prefetch、search_attributes 把 gin 条件封装成方法。
  2. PostgreSQL 相关
    • GIN 索引类型:gin( to_tsvector(..) )、gin( jsonb_path_ops )、gin( array )。
    • 走索引的运算符:@@、@>、&&、?&、?|。
    • 统计信息:EXPLAIN (ANALYZE, BUFFERS) 查看是否 Index Scan 及 Heap Fetches。
  3. 国内实战踩坑
    • 阿里云 RDS 默认开启 enable_seqscan=on,测试环境需手动 SET 或使用 pg_hint_plan。
    • 中文全文检索需配置 zhparser、jieba 插件,否则 to_tsvector 结果为空,GIN 形同虚设。
    • 分表分库场景下,DBIC 的 Storage::DBI::Replicated 会把条件下发到只读节点,需保证只读节点也建 GIN。

答案

下面给出一套可直接落地的写法,覆盖 DDL、ResultSet 封装、执行计划验证三个环节,面试时能把代码写在白板上即可拿到高分。

  1. 在 ResultSource 里声明 GIN 索引
package MyApp::Schema::Result::Article;
use base 'DBIx::Class::Core';
__PACKAGE__->table('article');
__PACKAGE__->add_columns(
    id         => { data_type => 'integer', is_auto_increment => 1 },
    title      => { data_type => 'text' },
    tsvector_col => { data_type => 'tsvector', is_nullable => 1 },
    tags       => { data_type => 'jsonb' },
);
__PACKAGE__->set_primary_key('id');

# 部署时自动建 GIN
sub sqlt_deploy_hook {
    my ($self, $sqlt_table) = @_;
    $sqlt_table->add_index(
        name   => 'article_tsvector_gin',
        fields => ['tsvector_col'],
        type   => 'GIN',
    );
    $sqlt_table->add_index(
        name   => 'article_tags_gin',
        fields => ['tags'],
        type   => 'GIN',
        # 使用 jsonb_path_ops 算子类,节省 50% 空间
        options => ['jsonb_path_ops'],
    );
}
  1. 创建触发器,保证 tsvector_col 实时更新
CREATE OR REPLACE FUNCTION article_tsvector_trigger() RETURNS trigger AS $$
BEGIN
  NEW.tsvector_col := to_tsvector('jiebacfg', COALESCE(NEW.title,''));
  RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER trg_article_tsvector
BEFORE INSERT OR UPDATE ON article
FOR EACH ROW EXECUTE FUNCTION article_tsvector_trigger();
  1. 封装 ResultSetComponent,让业务层无感知
package MyApp::Schema::ResultSet::Article;
use base 'DBIx::Class::ResultSet';
use strict;
use warnings;

# 全文检索走 GIN
sub search_by_tsquery {
    my ($self, $keyword) = @_;
    my $plain = $self->result_source->schema->storage
                 ->dbh_do(sub {
                     my ($storage, $dbh) = @_;
                     $dbh->selectrow_array(
                         'SELECT plainto_tsquery(?, ?)',
                         undef, 'jiebacfg', $keyword
                     );
                 });
    return $self->search(
        { 'tsvector_col' => { '@@' => \[ 'to_tsquery(?, ?)', 'jiebacfg', $keyword ] } },
        { bind => [ 'jiebacfg', $keyword ] }
    );
}

# jsonb 数组包含走 GIN
sub with_all_tags {
    my ($self, $tags) = @_;
    return $self->search(
        { tags => { '@>' => \[ '?', { json => $tags } ] } },
        { bind => [ { json => $tags } ] }
    );
}
  1. 调用与验证
my $rs = $schema->resultset('Article')
                ->search_by_tsquery('国产化替代')
                ->with_all_tags(['perl', 'postgresql'])
                ->prefetch('author');
print $rs->as_query;          # 查看生成的 SQL
# 输出:WHERE tsvector_col @@ to_tsquery('jiebacfg',?) AND tags @> ?
# 执行计划确认走 Index Scan

面试现场可再补一句:
“如果数据量超过千万,我会把 GIN 索引拆成分区本地索引,并通过 DBIC::ResultSet::RecursiveUpdate 批量维护,避免 VACUUM 抖动。”

拓展思考

  1. 混合索引场景:当查询同时包含 GIN 和 B-tree 条件时,PostgreSQL 14+ 可用 BitmapAnd 合并,但代价模型可能仍选 SeqScan;此时可用 pg_hint_plan 强制索引,或在 DBIC 里用 virtual::inlineview 先物化小表。
  2. 并行查询:RDS PostgreSQL 13 之后支持并行 GIN 扫描,需设置 max_parallel_workers_per_gather > 0;DBIC 侧无需改代码,但要在 Storage 的 on_connect_do 里 SET。
  3. 冷热分离:国内合规要求日志保存 5 年以上,可把历史表放到 OSS 外部表,GIN 索引只建在热表,通过 DBIC::Schema::Versioned 做分区切换。
  4. 国产化替代:华为 openGauss、阿里 PolarDB 对 GIN 接口完全兼容,但 jsonb_path_ops 算子类改名 jsonb_ops_path,需在 sqlt_deploy_hook 里根据 $self->schema->storage->sqlt_type 动态判断。