postgresql 优化/提高PSQL查询性能

nwsw7zdq  于 2023-03-12  发布在  PostgreSQL
关注(0)|答案(1)|浏览(206)

有什么方法可以进一步优化下面的查询吗?

select *,RANK () OVER (PARTITION BY jsondata->> 'id' ORDER BY pid desc ) as rank_number 
from xyz 
where jsondata ->> 'id' in (select jsondata ->> 'id' 
                        from xyz 
                            where pid= a) 
and pid <= a

关于色谱柱的一些详细信息:jsondata[jsonb],geo[几何图形],pid[bigint]
a是某个随机整数值。
表格结构

Table "public.xyz"
  Column  |           Type           | Collation | Nullable |                                       Default                                        
----------+--------------------------+-----------+----------+--------------------------------------------------------------------------------------
 gid      | text                     |           | not null | 
 jsondata | jsonb                    |           |          | 
 geo      | geometry.                |           |          | 
 pid      | bigint                   |           | not null | 
 i        | bigint                   |           | not null | 

Indexes:
    "xyzidx" PRIMARY KEY, btree (gid)
    "idx" btree (gid)

解释查询结果:

WindowAgg  (cost=2411885.51..2503195.23 rows=669100 width=1669)
  ->  Gather Merge  (cost=2411885.51..2489813.23 rows=669100 width=1661)
Workers Planned: 2
  ->  Sort  (cost=2410885.48..2411582.46 rows=278792 width=1661)
Sort Key: ((xyz.jsondata ->> 'id'::text)), xyz.pid DESC
  ->  Parallel Hash Semi Join  (cost=986665.67..1983541.38 rows=278792 width=1661)
Hash Cond: ((xyz.jsondata ->> 'id'::text) = (xyz.jsondata ->> 'id'::text))
  ->  Parallel Seq Scan on xyz  (cost=0.00..986664.95 rows=557584 width=1629)
Filter: (pid <= 97786)
  ->  Parallel Hash  (cost=986664.95..986664.95 rows=58 width=1536)
  ->  Parallel Seq Scan on xyz  (cost=0.00..986664.95 rows=58 width=1536)
Filter: (pid = 97786)

我尝试了下面的方法,但没有多大帮助

select A.jsondata,A.geo,RANK () OVER (PARTITION BY A.jsondata->> 'id' ORDER BY A.pid desc ) as rank_number 
from xyz A,xyz B  
Where A.jsondata->>'id' = B.jsondata->>'id' 
And B.pid = a
And A.pid<= a
ruarlubt

ruarlubt1#

如果不扫描整个表查看每个jsondata列,就无法满足查询 predicate (即WHERE条件)jsondata ->> 'id' in (something)
您可以将expression index放在jsondata ->> 'id'上。请尝试此操作。

CREATE INDEX jsondata_id ON xyz (jsondata ->> 'id');

如果你能让它起作用,它将有助于性能。

相关问题