Thread: Reverse btree indexes

Reverse btree indexes

From
Zach Aysan
Date:
Hey there! Thanks for putting together such wonderful documentation. I have a small suggestion for improvement.

 
Existing language:

for example, col LIKE 'foo%' or col ~ '^foo', but not col LIKE '%bar'.

Desired improvement:

 for example, col LIKE 'foo%' or col ~ '^foo', but not col LIKE '%bar', which would require a reversed index on the field. Postgres will automatically use the reverse index for LIKE '%bar'

Or if it doesn't:
 
for example, col LIKE 'foo%' or col ~ '^foo', but not col LIKE '%bar', which would require a reversed index on the field. To use the reversed index, query with reverse(col) like reverse('%bar').

I hope you all have a great day!

Zach
 

Re: Reverse btree indexes

From
"David G. Johnston"
Date:
On Tue, Jun 22, 2021 at 2:28 PM Zach Aysan <zachaysan@gmail.com> wrote:
Desired improvement:

 for example, col LIKE 'foo%' or col ~ '^foo', but not col LIKE '%bar', which would require a reversed index on the field. Postgres will automatically use the reverse index for LIKE '%bar'

Or if it doesn't:

It doesn't, otherwise the documentation wouldn't need to point out: but not col LIKE '%bar' ...

 
for example, col LIKE 'foo%' or col ~ '^foo', but not col LIKE '%bar', which would require a reversed index on the field. To use the reversed index, query with reverse(col) like reverse('%bar').


This type of commentary isn't usually something we include in the documentation...and I'm not too keen on "reversed index" as a phrase regardless.

David J.

Re: Reverse btree indexes

From
Alvaro Herrera
Date:
On 2021-Jun-22, David G. Johnston wrote:

> On Tue, Jun 22, 2021 at 2:28 PM Zach Aysan <zachaysan@gmail.com> wrote:

> >> for example, col LIKE 'foo%' or col ~ '^foo', but not col LIKE '%bar',
> >> which would require a reversed index on the field. To use the reversed
> >> index, query with reverse(col) like reverse('%bar').
> >
> This type of commentary isn't usually something we include in the
> documentation...and I'm not too keen on "reversed index" as a phrase
> regardless.

Maybe we can add it as a parenthical comment.  Something like

: The optimizer can also use a B-tree index for queries involving the
: pattern matching operators LIKE and ~ if the pattern is a constant and
: is anchored to the beginning of the string — for example, col LIKE
: 'foo%' or col ~ '^foo', but not col LIKE '%bar' (it is possible to
: use an expressional index to support queries such as the latter; see
: Section 11.7).  However, [...]

Then add an example in 11.7 Indexes on Expressions below the two
existing examples.  I think this is a noteworthy use of expressional
indexes; I've had to explain the reverse() idea a couple of times.

-- 
Álvaro Herrera                            39°49'30"S 73°17'W
"The eagle never lost so much time, as
when he submitted to learn of the crow." (William Blake)