N
N
NubasLol2018-09-26 11:00:32
PostgreSQL
NubasLol, 2018-09-26 11:00:32

Why doesn't Postgres use an index?

explain  analyze  select *
from "articles"
cross join plainto_tsquery(COALESCE('russian', get_current_ts_config()), 'search')
AS "tsquery" where searchable @@ "tsquery" order by "date" desc limit 10 offset 0;

Without sorting, the search is extremely fast, but with it, as practice shows (explain analyze), it scans all results for sorting.
Created an index
CREATE INDEX articles_desc_index ON articles (date DESC NULLS LAST)

But it's just ignored, any ideas how to fix it?
C order
Limit  (cost=2954.42..2954.44 rows=10 width=1520) (actual time=2999.486..2999.504 rows=10 loops=1)
  ->  Sort  (cost=2954.42..2956.15 rows=692 width=1520) (actual time=2999.484..2999.497 rows=10 loops=1)
        Sort Key: articles.published_at DESC
        Sort Method: top-N heapsort  Memory: 44kB
        ->  Nested Loop  (cost=457.36..2939.47 rows=692 width=1520) (actual time=28.453..2981.421 rows=5577 loops=1)
              ->  Function Scan on tsquery  (cost=0.00..0.01 rows=1 width=32) (actual time=0.004..0.006 rows=1 loops=1)
              ->  Bitmap Heap Scan on articles  (cost=457.36..2932.54 rows=692 width=1488) (actual time=28.441..2970.125 rows=5577 loops=1)
                    Recheck Cond: (searchable @@ tsquery.tsquery)
                    Heap Blocks: exact=5197
                    ->  Bitmap Index Scan on articles_searchable_index  (cost=0.00..457.19 rows=692 width=0) (actual time=27.755..27.755 rows=5587 loops=1)
                          Index Cond: (searchable @@ tsquery.tsquery)
Planning time: 0.180 ms
Execution time: 2999.576 ms

No sorting
Limit  (cost=457.36..493.23 rows=10 width=1520) (actual time=2.408..2.429 rows=10 loops=1)
  ->  Nested Loop  (cost=457.36..2939.47 rows=692 width=1520) (actual time=2.407..2.428 rows=10 loops=1)
        ->  Function Scan on tsquery  (cost=0.00..0.01 rows=1 width=32) (actual time=0.005..0.005 rows=1 loops=1)
        ->  Bitmap Heap Scan on articles  (cost=457.36..2932.54 rows=692 width=1488) (actual time=2.396..2.410 rows=10 loops=1)
              Recheck Cond: (searchable @@ tsquery.tsquery)
              Heap Blocks: exact=10
              ->  Bitmap Index Scan on articles_searchable_index  (cost=0.00..457.19 rows=692 width=0) (actual time=1.737..1.737 rows=5587 loops=1)
                    Index Cond: (searchable @@ tsquery.tsquery)
Planning time: 0.179 ms
Execution time: 2.477 ms

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Telepnev, 2018-09-26
@NubasLol

So you also write the sort as in the index (date DESC NULLS LAST)

S
stul5tul, 2018-09-26
@stul5tul

On small amounts of data without an index, it can be more efficient than with an index.
Fill the table with a huge amount of dummy data and check.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question