简体   繁体   English

如何通过索引PostgreSQL优化查询

[英]How to optimize query by index PostgreSQL

I want to fetch users that has 1 or more processed bets. 我想获取具有1个或多个已处理投注的用户。 I do this by using next sql: 我通过使用下一个sql来做到这一点:

SELECT user_id FROM bets 
WHERE bets.state in ('guessed', 'losed') 
GROUP BY user_id 
HAVING count(*) > 0;

But running EXPLAIN ANALYZE I noticed no index is used and query execution time is very high. 但是运行EXPLAIN ANALYZE我注意到没有使用索引,查询执行时间非常长。 I tried add partial index like: 我尝试添加部分索引,如:

CREATE INDEX processed_bets_index ON bets(state) WHERE state in ('guessed', 'losed');

But EXPLAIN ANALYZE output not changed: 但是EXPLAIN ANALYZE输出没有改变:

 HashAggregate  (cost=34116.36..34233.54 rows=9375 width=4) (actual time=235.195..237.623 rows=13310 loops=1)
   Filter: (count(*) > 0)
   ->  Seq Scan on bets  (cost=0.00..30980.44 rows=627184 width=4) (actual time=0.020..150.346 rows=626674 loops=1)
     Filter: ((state)::text = ANY ('{guessed,losed}'::text[]))
     Rows Removed by Filter: 20951
 Total runtime: 238.115 ms
 (6 rows)

Records with other statuses except (guessed, losed) a little. 记录除(猜测,失去)之外的其他状态。

How do I create proper index? 如何创建正确的索引?

I'm using PostgreSQL 9.3.4. 我正在使用PostgreSQL 9.3.4。

I assume that the state mostly consists of 'guessed' and 'losed', with maybe a few other states as well in there. 我假设国家主要由'猜测'和'失去'组成,可能还有其他一些状态。 So most probably the optimizer do not see the need to use the index since it would still fetch most of the rows. 所以很可能优化器没有看到需要使用索引,因为它仍然会获取大部分行。

What you do need is an index on the user_id, so perhaps something like this would work: 你需要的是user_id上的索引,所以这样的东西可能会起作用:

CREATE INDEX idx_bets_user_id_in_guessed_losed ON bets(user_id) WHERE state in ('guessed', 'losed');

Or, by not using a partial index: 或者,不使用部分索引:

CREATE INDEX idx_bets_state_user_id ON bets(state, user_id);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM