简体   繁体   English

PostgreSQL:哪个索引顺序更好?

[英]PostgreSQL: Which is the better index order?

What index(es) would be most helpful for running many of these PostgreSQL queries? 哪个索引对运行许多这些PostgreSQL查询最有帮助?

SELECT id, pair_time, user1, user2 
FROM pairs 
WHERE ? in (user1, user2) 
ORDER by pair_time

? = arbitrary username specified at run time. =在运行时指定的任意用户名。

I was thinking these two indexes: 我在想这两个索引:

CREATE INDEX ON pairs (user1, pair_time)
CREATE INDEX ON pairs (user2, pair_time)

But should the order be reversed? 但是,应该颠倒顺序吗?

CREATE INDEX ON pairs (pair_time, user1) 
CREATE INDEX ON pairs (pair_time, user2) 

Is there a better solution requiring just one index? 是否有只需要一个索引的更好的解决方案?

I do not know if Postgres will use any of those indexes wisely on this query. 我不知道Postgres是否会在此查询中明智地使用这些索引中的任何一个。

You might try this: 您可以尝试以下方法:

SELECT u.*
FROM ((SELECT id, pair_time, user1, user2
       FROM pairs
       WHERE user1 = ?
      ) UNION ALL
      (SELECT id, pair_time, user1, user2
       FROM pairs
       WHERE user2 = ?
      )
     ) u
ORDER by pair_time;

This will use indexes on pairs(user1) and pairs(user2) for each subquery. 这将对每个子查询使用pairs(user1)pairs(user2)索引。 The outer order by will require sorting the data. 外部order by将需要对数据进行排序。 I cannot think of a way off-hand to remove the outer sort. 我想不出一种简便的方法来删除外部类。

Another option would be to use a GIN index an an array of both columns: 另一种选择是使用GIN索引和两列的数组:

create index on pairs using gin ((array[user1, user2]) array_ops);

Then change your query to use compare arrays: 然后将查询更改为使用比较数组:

select id, pair_time, user1, user2 
from pairs
where array[user1, user2] && array[1234]
order by pair_time

I think regarding your below query 我认为关于您的以下查询

SELECT id, pair_time, user1, user2 FROM pairs WHERE ? in (user1, user2) ORDER by pair_time

below index will help better than others 2 index that you create 以下索引将比您创建的其他索引2更好

CREATE INDEX ON user_pairs (user1, pair_time)
CREATE INDEX ON user_pairs (user2, pair_time)

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

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