简体   繁体   中英

PostgreSQL: Which is the better index order?

What index(es) would be most helpful for running many of these PostgreSQL queries?

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.

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. The outer order by will require sorting the data. 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:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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