Re: [SQL] making 'like' queries quicker

Поиск
Список
Период
Сортировка
От Tom Lane
Тема Re: [SQL] making 'like' queries quicker
Дата
Msg-id 1560.945556061@sss.pgh.pa.us
обсуждение исходный текст
Ответ на Re: [SQL] making 'like' queries quicker  ("tjk@tksoft.com" <tjk@tksoft.com>)
Ответы Re: [SQL] making 'like' queries quicker  ("tjk@tksoft.com" <tjk@tksoft.com>)
Список pgsql-sql
"tjk@tksoft.com" <tjk@tksoft.com> writes:
> A general rule of thumb is that indexes
> only work on exact matches.

Troy's rule of thumb is correct, but there's an important additional
property of some types of indexes: you can scan them in order (for
whatever kind of "order" is imposed by the index comparison operator).
Postgres' btree indexes work that way, but hash indexes don't.

An ordered index can be used to process inequalities and range
queries as well as exact-match queries.  For example, with a btree
index you can do something likeWHERE lastname >= 'Smith' AND lastname <= 'Szekely'
fairly efficiently: you scan the portion of the index falling between
the given limits, and then extract the main-table records pointed to
by those index entries.

Therefore, it's practical to use a btree index to speed up match queries
that require a match at the start of the string.  For example, givenWHERE lastname LIKE 'Smith%'
Postgres will generate additional clauseslastname >= 'Smith' AND lastname <= 'Smith\377'
which can be used with a btree index to restrict the number of records
that have to be looked at.  You still have to do the LIKE comparison,
in general (consider LIKE 'Smith%Jr') but you don't have to do it for
every record in the table.

There isn't any obvious way to apply this trick for an unanchored match,
though (as in LIKE '%Smith%').

However, if you are actually interested in searching for whole words,
you could consider making an index that lists all of the whole words in
your target field, and doing an exact match with that index.  See
contrib/fulltextindex in the Postgres distribution for an example.
        regards, tom lane


В списке pgsql-sql по дате отправления:

Предыдущее
От:
Дата:
Сообщение: [Q] Merging two queries?
Следующее
От: Tom Lane
Дата:
Сообщение: Re: [SQL] [Q] Merging two queries?