如何在 PostgreSQL 中加快查询速度

How to speed up the query in PostgreSQL

我在 PostgreSQL 中有一个包含大数据的数据库(现在它大约有 46 GB,并且数据库会不断增长)。我在常用列上创建了索引并修改了配置文件:

shared_buffers = 1GB
temp_buffers = 256MB
work_mem = 512MB

但是这个查询还是很慢:

select distinct us_category_id as cat, count(h_user_id) as res from web_hits 
inner join users on h_user_id = us_id 
where (h_datetime)::date = ('2015-06-26')::date and us_category_id != ''
group by us_category_id

解释分析:

HashAggregate (cost=2870958.72..2870958.93 rows=21 width=9) (actual time=899141.683..899141.683 rows=0 loops=1)

Group Key: users.us_category_id, count(web_hits.h_user_id)
-> HashAggregate (cost=2870958.41..2870958.62 rows=21 width=9) (actual time=899141.681..899141.681 rows=0 loops=1)

Group Key: users.us_category_id
 -> Hash Join (cost=5974.98..2869632.11 rows=265259 width=9) (actual time=899141.679..899141.679 rows=0 loops=1)

Hash Cond: ((web_hits.h_user_id)::text = (users.us_id)::text)
-> Seq Scan on web_hits (cost=0.00..2857563.80 rows=275260 width=7) (actual time=899141.676..899141.676 rows=0 loops=1)
-> Seq Scan on web_hits (cost=0.00..2857563.80 rows=275260 width=7) (actual time=899141.676..899141.676 rows=0 loops=1)
Filter: ((h_datetime)::date = '2015-06-26'::date)

Rows Removed by Filter: 55051918
-> Hash (cost=4292.99..4292.99 rows=134559 width=10) (never executed)
-> Seq Scan on users (cost=0.00..4292.99 rows=134559 width=10) (never executed)
Filter: ((us_category_id)::text <> ''::text)

"Planning time: 1.309 ms"
"Execution time: 899141.789 ms"

日期已更改。 如何加快查询速度?

Table 和索引创建

CREATE TABLE web_hits (
  h_id integer NOT NULL DEFAULT nextval('w_h_seq'::regclass),
  h_user_id character varying,
  h_datetime timestamp without time zone,
  h_db_id character varying,
  h_voc_prefix character varying,
  ...
  h_bot_chek integer, -- 1-бот...
  CONSTRAINT w_h_pk PRIMARY KEY (h_id)
);
ALTER TABLE web_hits OWNER TO postgres;
COMMENT ON COLUMN web_hits.h_bot_chek IS '1-бот, 0-не бот';

CREATE INDEX h_datetime ON web_hits (h_datetime);
CREATE INDEX h_db_index ON web_hits (h_db_id COLLATE pg_catalog."default");
CREATE INDEX h_pref_index ON web_hits (h_voc_prefix COLLATE pg_catalog."default" text_pattern_ops);
CREATE INDEX h_user_index ON web_hits (h_user_id text_pattern_ops);

 CREATE TABLE users (
  us_id character varying NOT NULL,
  us_category_id character varying,
  ...
  CONSTRAINT user_pk PRIMARY KEY (us_id),
  CONSTRAINT cities_users_fk FOREIGN KEY (us_city_home)
      REFERENCES cities (city_id),
  CONSTRAINT countries_users_fk FOREIGN KEY (us_country_home)
      REFERENCES countries (country_id),
  CONSTRAINT organizations_users_fk FOREIGN KEY (us_institution_id)
      REFERENCES organizations (org_id),
  CONSTRAINT specialities_users_fk FOREIGN KEY (us_speciality_id)
      REFERENCES specialities (speciality_id),
  CONSTRAINT us_affiliation FOREIGN KEY (us_org_id)
      REFERENCES organizations (org_id),
  CONSTRAINT us_category FOREIGN KEY (us_category_id)
      REFERENCES categories (cat_id),
  CONSTRAINT us_reading_room FOREIGN KEY (us_reading_room_id)
      REFERENCES reading_rooms (rr_id)
);
ALTER TABLE users OWNER TO sveta;
COMMENT ON COLUMN users.us_type IS '0-аноним, 1-читатель, 2-удаленный';

CREATE INDEX us_cat_index ON users (us_category_id);
CREATE INDEX us_user_index ON users (us_id text_pattern_ops);

首先,distinct 不是必需的:

select u.us_category_id as cat, count(h_user_id) as res
from web_hits h inner join
     users u
     on h.h_user_id = u.us_id 
where (h.h_datetime)::date = '2015-06-26'::date and
      u.us_category_id <> ''
group by u.us_category_id

其次,您要删除列上的转换。所以:

select u.us_category_id as cat, count(h_user_id) as res
from web_hits h inner join
     users u
     on h.h_user_id = u.us_id 
where (h.h_datetime >= '2015-06-26' and h.h_datetime < '2015-06-27) and
      u.us_category_id <> ''
group by u.us_category_id;

那么,下面的索引应该有助于查询:web_hits(h_datetime, h_user_id)。在 users(us_id, us_category_id).

上建立索引也可能是有益的

问题中缺少基本信息。我将根据有根据的猜测来回答我的部分问题。 web_hits.h_user_id 有时为 NULL,就像您在评论中添加的那样。

查询

基本上,无论如何都可以将查询简化/改进为:

SELECT u.us_category_id AS cat, count(*) AS res
FROM   users    u
JOIN   web_hits w ON w.h_user_id = u.us_id
WHERE  w.h_datetime >= '2015-06-26 0:0'::timestamp
AND    w.h_datetime <  '2015-06-27 0:0'::timestamp
AND    w.h_user_id IS NOT NULL  -- remove irrelevant rows, match index
AND    u.us_category_id <> ''
GROUP  BY 1;
  • DISTINCT 显然是不必要的,因为你已经 group by us_category_id(比如 )。

  • 满足条件sargable可以使用索引:

    • How do I match an entire day to a datetime field?
  • 由于您加入了列 w.h_user_id,因此从逻辑上讲,结果行在此列中为 NOT NULLcount(*) 在这种情况下是等效的,而且速度更快。

  • 条件 h_user_id IS NOT NULL 似乎是多余的,因为 NULL 在 JOIN 中被消除了,但它允许使用具有匹配条件的部分索引(见下文)。

  • users.us_id(因此 web_hits.h_user_id)可能不应该具有数据类型 varcharcharacter varying)。对于巨大 table 中的 PK / FK 列来说,这是一种低效的数据类型。如果必须,请使用 int or bigint (or uuid 之类的数字数据类型)。 us_category_id的类似考虑:应该是integer或相关的。

  • 标准 SQL 不等式运算符是 <>。使用它代替同样支持的 !=.

  • 使用 table 限定词以避免歧义 - 并且在任何情况下都可以让 public 论坛中的读者清楚地了解您的查询。

优化

进一步假设:

  • users.us_category_id <> '' 对于大多数行都是正确的。
  • 包含 web_hits.h_user_id IS NOT NULL 的大部分或所有行都被计算在内。

这样会更快,但是:

SELECT u.us_category_id AS cat, sum(ct) AS res
FROM   users u
JOIN  (
   SELECT h_user_id, count(*) AS ct
   FROM   web_hits
   WHERE  h_datetime >= '2015-06-26 0:0'::timestamp
   AND    h_datetime <  '2015-06-27 0:0'::timestamp
   AND    h_user_id IS NOT NULL  -- remove irrelevant rows, match index
   GROUP  BY 1
   ) w ON w.h_user_id = u.us_id
AND    u.us_category_id <> ''
GROUP  BY 1;

索引

无论哪种方式,partial indexes 最适合您的情况:

1.

CREATE INDEX wh_usid_datetime_idx ON web_hits(h_user_id, h_datetime)
WHERE  h_user_id IS NOT NULL;

从索引中删除 web_hits.h_user_id IS NULL 的行。

按照的顺序,而不是建议的相反顺序。详细解释:

2.

CREATE INDEX us_usid_cat_not_empty_idx ON users(us_id)
WHERE  us_category_id <> '';

这会小很多,因为我们不会在索引中存储可能很长的 varcharus_category_id - 无论如何我们都不需要它。我们只需要知道它是 <> ''。如果您有 integer 列,则此注意事项不适用。

并且我们还排除了 us_category_id 中具有 ''NULL 的行,从而使索引更小。

您必须权衡特殊索引的维护成本和它们的好处。如果你 运行 查询很多匹配条件,它会付费,否则,它可能不会,更通用的索引可能总体上更好。


当然,performance optimization 上的所有常用建议也适用。

坦率地说,您的查询不正确,您的设置中有许多项目是可疑的。处理像你这样巨大的 tables,你可能会考虑寻求专业帮助。