bandian
V2EX  ›  问与答

在百万、千万级数据的一张 PostgreSQL 表中如何高效搜索一个指定的内容

  •  
  •   bandian · Nov 23, 2020 · 1683 views
    This topic created in 2087 days ago, the information mentioned may be changed or developed.

    待搜索的字段为 json 类型,要做的是模糊匹配。

    如果直接使用 like 匹配,性能上感觉应该会爆炸,不知道有没有什么原生的比较高效或者耗时短的查询方式。

    GBdG6clg2Jy17ua5
        1
    GBdG6clg2Jy17ua5  
       Nov 23, 2020 via iPhone
    mysql 可以创建虚拟字段,映射要查询的 json 字段,不知道 postgresql 有没有
    abcfyk
        2
    abcfyk  
       Nov 23, 2020
    要么牺牲写速度,解析 json 出来再写,
    要么牺牲读速度,直接存 json,读的时候解析

    非要存 pg,就这两个方向,其他的优化都是隔靴搔痒
    MoYi123
        3
    MoYi123  
       Nov 23, 2020
    不清楚你具体要怎样做模糊查询,举几种常见场景
    1. 查询 json 中的第一层存在 key 为 1 的行,比如{"1":"abc"},需要在 json 列建 gin 索引
    create index test_data1_gin on test using gin (data1);
    select * from test where data1 ? '1';

    2. 查询 json 中某个具体键的值,比如{'age':18},需要对 json->>'age'建索引
    create index test_data1_btree on test using btree ((data1 ->> 'age'));
    select * from test where data1 ->> 'age' = 18;

    3. like '":2' 比如'{"1":2}', 那这一列不应该存为 json,应该存为 text,然后加上 gin 索引
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1175 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 17:43 · PVG 01:43 · LAX 10:43 · JFK 13:43
    ♥ Do have faith in what you're doing.