SlideShare a Scribd company logo
Full Text Search in
PostgreSQL
Aleksander Alekseev
Agenda
● Intro
● Full text search basics
● Fuzzy full text search
● And some other topics
Intro
Полнотекстовый поиск в PostgreSQL / Александр Алексеев (Postgres Professional)
Well-known FTS Solutions
● ElasticSearch
● Solr
● Sphinx
Why Use FTS in PostgreSQL
● More or less as good as specialized software
● No data duplication
● Data is always consistent
● No need to install and maintain anything except PostgreSQL
Full Text Search Basics
to_tsvector
# SELECT to_tsvector('No need to install and maintain anything except PostgreSQL');
'anyth':7 'except':8 'instal':4 'maintain':6 'need':2 'postgresql':9
(1 row)
# SELECT to_tsvector('russian',
'Не нужно устанавливать и поддерживать ничего кроме PostgreSQL');
'postgresql':8 'кром':7 'нужн':2 'поддержива':5 'устанавлива':3
(1 row)
to_tsquery
# SELECT to_tsquery('install | maintain');
'instal' | 'maintain'
(1 row)
# SELECT to_tsquery('russian', 'устанавливать & поддерживать');
'устанавлива' & 'поддержива'
(1 row)
plainto_tsquery & phraseto_tsquery
# SELECT plainto_tsquery('install maintain');
'instal' & 'maintain'
(1 row)
# SELECT phraseto_tsquery('russian', 'устанавливать поддерживать');
'устанавлива' <-> 'поддержива'
(1 row)
tsvector @@ tsquery
# SELECT to_tsvector('No need to install and maintain anything except
PostgreSQL') @@ plainto_tsquery('install maintain') AS match;
match
-------
t
Indexes: GIN or GiST?
GIN vs GiST:
● GIN
○ fast search, not very fast updates
○ better for static data
● GiST
○ slow search, faster updates
○ better for dynamic data
If you are not sure use GIN.
Practice: 1 / 3
CREATE TABLE IF NOT EXISTS
articles(id serial primary key, title varchar(128), content text);
-- https://meta.wikimedia.org/wiki/Data_dump_torrents#enwiki
-- https://github.com/afiskon/postgresql-fts-example
COPY articles FROM PROGRAM 'zcat /path/to/articles.copy.gz';
Practice: 2 / 3
CREATE OR REPLACE FUNCTION make_tsvector(title text, content text)
RETURNS tsvector AS $$
BEGIN
RETURN (setweight(to_tsvector('english', title),'A') ||
setweight(to_tsvector('english', content), 'B'));
END
$$ LANGUAGE 'plpgsql' IMMUTABLE;
Practice: 3 / 3
CREATE INDEX IF NOT EXISTS idx_fts_articles ON articles
USING gin(make_tsvector(title, content));
SELECT id, title FROM articles WHERE
make_tsvector(title, content) @@ to_tsquery('bjarne <-> stroustrup');
2470 | Binary search algorithm
2129 | Bell Labs
2130 | Bjarne Stroustrup
3665 | C (programming language)
ts_headline: 1 / 2
SELECT id, ts_headline(title, q) FROM articles,
to_tsquery('bjarne <-> stroustrup') AS q -- !!!
WHERE make_tsvector(title, content) @@ q;
2470 | Binary search algorithm
2129 | Bell Labs
2130 | <b>Bjarne</b> <b>Stroustrup</b>
ts_headline: 2 / 2
SELECT id, ts_headline(title, q, 'StartSel=<em>, StopSel=</em>') -- !!!
FROM articles, to_tsquery('bjarne <-> stroustrup') as q
WHERE make_tsvector(title, content) @@ q;
2470 | Binary search algorithm
2129 | Bell Labs
2130 | <em>Bjarne</em> <em>Stroustrup</em>
ts_rank
SELECT id, ts_headline(title, q, 'StartSel=<em>, StopSel=</em>')
FROM articles, to_tsquery('bjarne <-> stroustrup') as q
WHERE make_tsvector(title, content) @@ q
ORDER BY ts_rank(make_tsvector(title, content), q) DESC;
2130 | <em>Bjarne</em> <em>Stroustrup</em>
3665 | C (programming language)
6266 | Edsger W. Dijkstra
RUM
$ git clone git@github.com:postgrespro/rum.git
$ cd rum
$ USE_PGXS=1 make install
$ USE_PGXS=1 make installcheck
psql> CREATE EXTENSION rum;
Fuzzy Full Text Search
pg_trgm: 1 / 4
create extension pg_trgm;
create index articles_trgm_idx on articles using gin (title gin_trgm_ops);
pg_trgm: 2 / 4
select show_trgm(title) from articles limit 3;
show_trgm | {" a"," ac",acc,ble,cce,ces,com,eco,ess,ibl,ing,lec,mpu,...
show_trgm | {" a"," an",ana,arc,chi,his,ism,nar,rch,"sm "}
show_trgm | {" a"," af",afg,anh,ani,fgh,gha,han,his,ist,nhi,nis,ory,...
pg_trgm: 3 / 4
select title, similarity(title, 'Straustrup') from articles where title % 'Straustrup';
-[ RECORD 1 ]-----------------
title | Bjarne Stroustrup
similarity | 0.35
pg_trgm: 4 / 4
psql> select show_limit();
-[ RECORD 1 ]---
show_limit | 0.3
psql> select set_limit(0.4);
-[ RECORD 1 ]--
set_limit | 0.4
pg_trgm: like / ilike queries
# explain select title from articles where title LIKE '%Stroustrup%';
QUERY PLAN
---------------------------------------------------------------------------------
Bitmap Heap Scan on articles (cost=60.02..71.40 rows=3 width=16)
Recheck Cond: ((title)::text ~~ '%Stroustrup%'::text)
-> Bitmap Index Scan on articles_trgm_idx (cost=0.00..60.02 rows=3...
Index Cond: ((title)::text ~~ '%Stroustrup%'::text)
pg_trgm: regular expressions
# explain select title from articles where title ~* 'Stroustrup';
QUERY PLAN
---------------------------------------------------------------------------------
Bitmap Heap Scan on articles (cost=60.02..71.40 rows=3 width=16)
Recheck Cond: ((title)::text ~* 'Stroustrup'::text)
-> Bitmap Index Scan on articles_trgm_idx (cost=0.00..60.02 rows=3...
Index Cond: ((title)::text ~* 'Stroustrup'::text)
See also
● The pg_trgm module provides functions and operators for determining the
similarity of alphanumeric text based on trigram matching
○ https://www.postgresql.org/docs/current/static/pgtrgm.html
● Full Text Search support for JSON and JSONB
○ https://www.depesz.com/2017/04/04/waiting-for-postgresql-10-full-text-search-support-for-json
-and-jsonb/
● RUM access method
○ https://github.com/postgrespro/rum
Thank you for your attention!
● http://eax.me/
● http://devzen.ru/
Bonus Slide!
GIN & arrays
create table vec_test(id serial primary key, tags int[]);
create index vec_test_gin on vec_test using gin(tags);
insert into vec_test (tags) values ('{111,222,333}');
select * from vec_test where '{111}' <@ tags;
select * from vec_test where '{111}' @> tags;
select * from vec_test where '{111}' = tags;
-- intersection is not empty
select * from vec_test where '{111}' && tags;

More Related Content

What's hot (20)

PDF
What is the best full text search engine for Python?
Andrii Soldatenko
 
PDF
John Melesky - Federating Queries Using Postgres FDW @ Postgres Open
PostgresOpen
 
PDF
Rank Your Results with PostgreSQL Full Text Search (from PGConf2015)
Jamey Hanson
 
PDF
JDD 2016 - Tomasz Borek - DB for next project? Why, Postgres, of course
PROIDEA
 
PDF
2015-12-05 Александр Коротков, Иван Панченко - Слабо-структурированные данные...
HappyDev
 
PDF
PyCon Russian 2015 - Dive into full text search with python.
Andrii Soldatenko
 
PPTX
PostgreSQL 9.4 JSON Types and Operators
Nicholas Kiraly
 
PDF
Flexible Indexing with Postgres
EDB
 
PDF
PostgreSQL 9.4, 9.5 and Beyond @ COSCUP 2015 Taipei
Satoshi Nagayasu
 
PDF
InfluxDB IOx Tech Talks: Intro to the InfluxDB IOx Read Buffer - A Read-Optim...
InfluxData
 
PDF
PostgreSQL query planner's internals
Alexey Ermakov
 
PDF
Pgbr 2013 fts
Emanuel Calvo
 
PPTX
Bucket Your Partitions Wisely (Markus Höfer, codecentric AG) | Cassandra Summ...
DataStax
 
PDF
Tests unitaires pour PostgreSQL avec pgTap
Rodolphe Quiédeville
 
PDF
Advanced Apache Cassandra Operations with JMX
zznate
 
PPTX
Cassandra Data Modeling - Practical Considerations @ Netflix
nkorla1share
 
ODP
PostgreSQL Administration for System Administrators
Command Prompt., Inc
 
PDF
How to teach an elephant to rock'n'roll
PGConf APAC
 
PDF
PostgreSQL 9.6 새 기능 소개
PgDay.Seoul
 
PPTX
P4 2017 io
Prof. Wim Van Criekinge
 
What is the best full text search engine for Python?
Andrii Soldatenko
 
John Melesky - Federating Queries Using Postgres FDW @ Postgres Open
PostgresOpen
 
Rank Your Results with PostgreSQL Full Text Search (from PGConf2015)
Jamey Hanson
 
JDD 2016 - Tomasz Borek - DB for next project? Why, Postgres, of course
PROIDEA
 
2015-12-05 Александр Коротков, Иван Панченко - Слабо-структурированные данные...
HappyDev
 
PyCon Russian 2015 - Dive into full text search with python.
Andrii Soldatenko
 
PostgreSQL 9.4 JSON Types and Operators
Nicholas Kiraly
 
Flexible Indexing with Postgres
EDB
 
PostgreSQL 9.4, 9.5 and Beyond @ COSCUP 2015 Taipei
Satoshi Nagayasu
 
InfluxDB IOx Tech Talks: Intro to the InfluxDB IOx Read Buffer - A Read-Optim...
InfluxData
 
PostgreSQL query planner's internals
Alexey Ermakov
 
Pgbr 2013 fts
Emanuel Calvo
 
Bucket Your Partitions Wisely (Markus Höfer, codecentric AG) | Cassandra Summ...
DataStax
 
Tests unitaires pour PostgreSQL avec pgTap
Rodolphe Quiédeville
 
Advanced Apache Cassandra Operations with JMX
zznate
 
Cassandra Data Modeling - Practical Considerations @ Netflix
nkorla1share
 
PostgreSQL Administration for System Administrators
Command Prompt., Inc
 
How to teach an elephant to rock'n'roll
PGConf APAC
 
PostgreSQL 9.6 새 기능 소개
PgDay.Seoul
 

Viewers also liked (20)

PPTX
WAMP[-proto] как основа композитных SOA-приложений и его имплементация на Lua...
Ontico
 
PPTX
Организации в бирюзовом цвете / Мария Груздева (НИУ ВШЭ)
Ontico
 
PDF
Сложности performance-тестирования / Андрей Акиньшин (JetBrains)
Ontico
 
PPTX
Искусство предсказания: как давать более точные оценки времени проекта / Андр...
Ontico
 
PDF
Cassandra для хранения метаданных: успехи и провалы / Андрей Смирнов (Virtust...
Ontico
 
PPTX
Как сделать сложное простым. История создания Проект1917 / Сергей Спорышев (I...
Ontico
 
PPTX
Ошибки проектирования высоконагруженных проектов / Максим Ехлаков (OneTwoRent)
Ontico
 
PDF
ТОП ошибок в инфраструктуре, мешающих высоким нагрузкам / Андрей Половов (Флант)
Ontico
 
PDF
BigMemory - работа с сотнями миллионов бизнес-объектов / Дмитрий Хмаладзе (Ag...
Ontico
 
PPTX
Безболезненный Fallback cache на Scala / Олег Нижников (Tinkoff.ru)
Ontico
 
PDF
Блокчейн. Lego для интересующихся / Александр Боргардт (GolosCore)
Ontico
 
PDF
Рост с нуля до 15000 сообщений в секунду. Мучительный и поучительный / Юрий К...
Ontico
 
PPTX
Как построить хороший performance review: опыт Badoo / Алексей Рыбак (Badoo)
Ontico
 
PPTX
Приключения проекта от компьютера разработчика до серьезных нагрузок / Андрей...
Ontico
 
PDF
После подключения DDoS-защиты: как "положат" Ваши ресурсы / Рамиль Хантимиров...
Ontico
 
PDF
Проксирование HTTP-запросов web-акселератором / Александр Крижановский (Tempe...
Ontico
 
PDF
DevOps-трансформация Альфа-Банка / Антон Исанин (Альфа-Банк)
Ontico
 
PDF
Все, что тимлид должен знать о найме и увольнении / Степан Овчинников (ИНТЕРВ...
Ontico
 
PDF
Лучшие практики CI/CD с Kubernetes и GitLab / Дмитрий Столяров (Флант)
Ontico
 
PPTX
Погружение в виртуальную память и большие страницы / Константин Новаковский (...
Ontico
 
WAMP[-proto] как основа композитных SOA-приложений и его имплементация на Lua...
Ontico
 
Организации в бирюзовом цвете / Мария Груздева (НИУ ВШЭ)
Ontico
 
Сложности performance-тестирования / Андрей Акиньшин (JetBrains)
Ontico
 
Искусство предсказания: как давать более точные оценки времени проекта / Андр...
Ontico
 
Cassandra для хранения метаданных: успехи и провалы / Андрей Смирнов (Virtust...
Ontico
 
Как сделать сложное простым. История создания Проект1917 / Сергей Спорышев (I...
Ontico
 
Ошибки проектирования высоконагруженных проектов / Максим Ехлаков (OneTwoRent)
Ontico
 
ТОП ошибок в инфраструктуре, мешающих высоким нагрузкам / Андрей Половов (Флант)
Ontico
 
BigMemory - работа с сотнями миллионов бизнес-объектов / Дмитрий Хмаладзе (Ag...
Ontico
 
Безболезненный Fallback cache на Scala / Олег Нижников (Tinkoff.ru)
Ontico
 
Блокчейн. Lego для интересующихся / Александр Боргардт (GolosCore)
Ontico
 
Рост с нуля до 15000 сообщений в секунду. Мучительный и поучительный / Юрий К...
Ontico
 
Как построить хороший performance review: опыт Badoo / Алексей Рыбак (Badoo)
Ontico
 
Приключения проекта от компьютера разработчика до серьезных нагрузок / Андрей...
Ontico
 
После подключения DDoS-защиты: как "положат" Ваши ресурсы / Рамиль Хантимиров...
Ontico
 
Проксирование HTTP-запросов web-акселератором / Александр Крижановский (Tempe...
Ontico
 
DevOps-трансформация Альфа-Банка / Антон Исанин (Альфа-Банк)
Ontico
 
Все, что тимлид должен знать о найме и увольнении / Степан Овчинников (ИНТЕРВ...
Ontico
 
Лучшие практики CI/CD с Kubernetes и GitLab / Дмитрий Столяров (Флант)
Ontico
 
Погружение в виртуальную память и большие страницы / Константин Новаковский (...
Ontico
 
Ad

Similar to Полнотекстовый поиск в PostgreSQL / Александр Алексеев (Postgres Professional) (20)

PPTX
PostgreSQL - It's kind've a nifty database
Barry Jones
 
PDF
Postgresql search demystified
javier ramirez
 
PDF
The State of (Full) Text Search in PostgreSQL 12
Jimmy Angelakos
 
PDF
fts.pdf
AltairFonseca3
 
PDF
Full Text Search In PostgreSQL
Karwin Software Solutions LLC
 
PPTX
Postgres indexes: how to make them work for your application
Bartosz Sypytkowski
 
PDF
Ten Reasons Why You Should Prefer PostgreSQL to MySQL
anandology
 
PPTX
Syntactic sugar in postgre sql
Antony Abramchenko
 
PDF
PostgreSQL: Advanced indexing
Hans-Jürgen Schönig
 
PDF
Syntactic sugar in Postgre SQL
Antony Abramchenko
 
PDF
Indexing Complex PostgreSQL Data Types
Jonathan Katz
 
PDF
Postgres vs Elasticsearch while enriching data - Vlad Somov | Ruby Meditaiton...
Ruby Meditation
 
PPTX
Postgres indexes
Bartosz Sypytkowski
 
PDF
Postgres performance for humans
Craig Kerstiens
 
PDF
PostgreSQL: Advanced features in practice
Jano Suchal
 
PDF
Pg for web developer
Long Nguyen
 
PDF
Flexible Indexing with Postgres
EDB
 
PDF
nGram full text search (by 이성욱)
I Goo Lee.
 
PDF
SQLite
Kirill Zotin
 
PDF
query-optimization-techniques_talk.pdf
garos1
 
PostgreSQL - It's kind've a nifty database
Barry Jones
 
Postgresql search demystified
javier ramirez
 
The State of (Full) Text Search in PostgreSQL 12
Jimmy Angelakos
 
Full Text Search In PostgreSQL
Karwin Software Solutions LLC
 
Postgres indexes: how to make them work for your application
Bartosz Sypytkowski
 
Ten Reasons Why You Should Prefer PostgreSQL to MySQL
anandology
 
Syntactic sugar in postgre sql
Antony Abramchenko
 
PostgreSQL: Advanced indexing
Hans-Jürgen Schönig
 
Syntactic sugar in Postgre SQL
Antony Abramchenko
 
Indexing Complex PostgreSQL Data Types
Jonathan Katz
 
Postgres vs Elasticsearch while enriching data - Vlad Somov | Ruby Meditaiton...
Ruby Meditation
 
Postgres indexes
Bartosz Sypytkowski
 
Postgres performance for humans
Craig Kerstiens
 
PostgreSQL: Advanced features in practice
Jano Suchal
 
Pg for web developer
Long Nguyen
 
Flexible Indexing with Postgres
EDB
 
nGram full text search (by 이성욱)
I Goo Lee.
 
SQLite
Kirill Zotin
 
query-optimization-techniques_talk.pdf
garos1
 
Ad

More from Ontico (20)

PDF
One-cloud — система управления дата-центром в Одноклассниках / Олег Анастасье...
Ontico
 
PDF
Масштабируя DNS / Артем Гавриченков (Qrator Labs)
Ontico
 
PPTX
Создание BigData-платформы для ФГУП Почта России / Андрей Бащенко (Luxoft)
Ontico
 
PDF
Готовим тестовое окружение, или сколько тестовых инстансов вам нужно / Алекса...
Ontico
 
PDF
Новые технологии репликации данных в PostgreSQL / Александр Алексеев (Postgre...
Ontico
 
PDF
PostgreSQL Configuration for Humans / Alvaro Hernandez (OnGres)
Ontico
 
PDF
Inexpensive Datamasking for MySQL with ProxySQL — Data Anonymization for Deve...
Ontico
 
PDF
Опыт разработки модуля межсетевого экранирования для MySQL / Олег Брославский...
Ontico
 
PPTX
ProxySQL Use Case Scenarios / Alkin Tezuysal (Percona)
Ontico
 
PPTX
MySQL Replication — Advanced Features / Петр Зайцев (Percona)
Ontico
 
PDF
Внутренний open-source. Как разрабатывать мобильное приложение большим количе...
Ontico
 
PPTX
Подробно о том, как Causal Consistency реализовано в MongoDB / Михаил Тюленев...
Ontico
 
PPTX
Балансировка на скорости проводов. Без ASIC, без ограничений. Решения NFWare ...
Ontico
 
PDF
Перехват трафика — мифы и реальность / Евгений Усков (Qrator Labs)
Ontico
 
PPT
И тогда наверняка вдруг запляшут облака! / Алексей Сушков (ПЕТЕР-СЕРВИС)
Ontico
 
PPTX
Как мы заставили Druid работать в Одноклассниках / Юрий Невиницин (OK.RU)
Ontico
 
PPTX
Разгоняем ASP.NET Core / Илья Вербицкий (WebStoating s.r.o.)
Ontico
 
PPTX
100500 способов кэширования в Oracle Database или как достичь максимальной ск...
Ontico
 
PPTX
Apache Ignite Persistence: зачем Persistence для In-Memory, и как он работает...
Ontico
 
PDF
Механизмы мониторинга баз данных: взгляд изнутри / Дмитрий Еманов (Firebird P...
Ontico
 
One-cloud — система управления дата-центром в Одноклассниках / Олег Анастасье...
Ontico
 
Масштабируя DNS / Артем Гавриченков (Qrator Labs)
Ontico
 
Создание BigData-платформы для ФГУП Почта России / Андрей Бащенко (Luxoft)
Ontico
 
Готовим тестовое окружение, или сколько тестовых инстансов вам нужно / Алекса...
Ontico
 
Новые технологии репликации данных в PostgreSQL / Александр Алексеев (Postgre...
Ontico
 
PostgreSQL Configuration for Humans / Alvaro Hernandez (OnGres)
Ontico
 
Inexpensive Datamasking for MySQL with ProxySQL — Data Anonymization for Deve...
Ontico
 
Опыт разработки модуля межсетевого экранирования для MySQL / Олег Брославский...
Ontico
 
ProxySQL Use Case Scenarios / Alkin Tezuysal (Percona)
Ontico
 
MySQL Replication — Advanced Features / Петр Зайцев (Percona)
Ontico
 
Внутренний open-source. Как разрабатывать мобильное приложение большим количе...
Ontico
 
Подробно о том, как Causal Consistency реализовано в MongoDB / Михаил Тюленев...
Ontico
 
Балансировка на скорости проводов. Без ASIC, без ограничений. Решения NFWare ...
Ontico
 
Перехват трафика — мифы и реальность / Евгений Усков (Qrator Labs)
Ontico
 
И тогда наверняка вдруг запляшут облака! / Алексей Сушков (ПЕТЕР-СЕРВИС)
Ontico
 
Как мы заставили Druid работать в Одноклассниках / Юрий Невиницин (OK.RU)
Ontico
 
Разгоняем ASP.NET Core / Илья Вербицкий (WebStoating s.r.o.)
Ontico
 
100500 способов кэширования в Oracle Database или как достичь максимальной ск...
Ontico
 
Apache Ignite Persistence: зачем Persistence для In-Memory, и как он работает...
Ontico
 
Механизмы мониторинга баз данных: взгляд изнутри / Дмитрий Еманов (Firebird P...
Ontico
 

Recently uploaded (20)

PPTX
VITEEE 2026 Exam Details , Important Dates
SonaliSingh127098
 
PPTX
What is Shot Peening | Shot Peening is a Surface Treatment Process
Vibra Finish
 
PPTX
Arduino Based Gas Leakage Detector Project
CircuitDigest
 
PPT
PPT2_Metal formingMECHANICALENGINEEIRNG .ppt
Praveen Kumar
 
PDF
Reasons for the succes of MENARD PRESSUREMETER.pdf
majdiamz
 
PDF
smart lot access control system with eye
rasabzahra
 
PPTX
The Role of Information Technology in Environmental Protectio....pptx
nallamillisriram
 
PPTX
fatigue in aircraft structures-221113192308-0ad6dc8c.pptx
aviatecofficial
 
DOC
MRRS Strength and Durability of Concrete
CivilMythili
 
PPTX
Evaluation and thermal analysis of shell and tube heat exchanger as per requi...
shahveer210504
 
PDF
AI TECHNIQUES FOR IDENTIFYING ALTERATIONS IN THE HUMAN GUT MICROBIOME IN MULT...
vidyalalltv1
 
PPT
Carmon_Remote Sensing GIS by Mahesh kumar
DhananjayM6
 
PPTX
Knowledge Representation : Semantic Networks
Amity University, Patna
 
PPTX
Product Development & DevelopmentLecture02.pptx
zeeshanwazir2
 
PPTX
Solar Thermal Energy System Seminar.pptx
Gpc Purapuza
 
PPTX
Introduction to Basic Renewable Energy.pptx
examcoordinatormesu
 
PPTX
Presentation 2.pptx AI-powered home security systems Secure-by-design IoT fr...
SoundaryaBC2
 
PDF
International Journal of Information Technology Convergence and services (IJI...
ijitcsjournal4
 
PPTX
MATLAB : Introduction , Features , Display Windows, Syntax, Operators, Graph...
Amity University, Patna
 
PDF
Design Thinking basics for Engineers.pdf
CMR University
 
VITEEE 2026 Exam Details , Important Dates
SonaliSingh127098
 
What is Shot Peening | Shot Peening is a Surface Treatment Process
Vibra Finish
 
Arduino Based Gas Leakage Detector Project
CircuitDigest
 
PPT2_Metal formingMECHANICALENGINEEIRNG .ppt
Praveen Kumar
 
Reasons for the succes of MENARD PRESSUREMETER.pdf
majdiamz
 
smart lot access control system with eye
rasabzahra
 
The Role of Information Technology in Environmental Protectio....pptx
nallamillisriram
 
fatigue in aircraft structures-221113192308-0ad6dc8c.pptx
aviatecofficial
 
MRRS Strength and Durability of Concrete
CivilMythili
 
Evaluation and thermal analysis of shell and tube heat exchanger as per requi...
shahveer210504
 
AI TECHNIQUES FOR IDENTIFYING ALTERATIONS IN THE HUMAN GUT MICROBIOME IN MULT...
vidyalalltv1
 
Carmon_Remote Sensing GIS by Mahesh kumar
DhananjayM6
 
Knowledge Representation : Semantic Networks
Amity University, Patna
 
Product Development & DevelopmentLecture02.pptx
zeeshanwazir2
 
Solar Thermal Energy System Seminar.pptx
Gpc Purapuza
 
Introduction to Basic Renewable Energy.pptx
examcoordinatormesu
 
Presentation 2.pptx AI-powered home security systems Secure-by-design IoT fr...
SoundaryaBC2
 
International Journal of Information Technology Convergence and services (IJI...
ijitcsjournal4
 
MATLAB : Introduction , Features , Display Windows, Syntax, Operators, Graph...
Amity University, Patna
 
Design Thinking basics for Engineers.pdf
CMR University
 

Полнотекстовый поиск в PostgreSQL / Александр Алексеев (Postgres Professional)

  • 1. Full Text Search in PostgreSQL Aleksander Alekseev
  • 2. Agenda ● Intro ● Full text search basics ● Fuzzy full text search ● And some other topics
  • 5. Well-known FTS Solutions ● ElasticSearch ● Solr ● Sphinx
  • 6. Why Use FTS in PostgreSQL ● More or less as good as specialized software ● No data duplication ● Data is always consistent ● No need to install and maintain anything except PostgreSQL
  • 8. to_tsvector # SELECT to_tsvector('No need to install and maintain anything except PostgreSQL'); 'anyth':7 'except':8 'instal':4 'maintain':6 'need':2 'postgresql':9 (1 row) # SELECT to_tsvector('russian', 'Не нужно устанавливать и поддерживать ничего кроме PostgreSQL'); 'postgresql':8 'кром':7 'нужн':2 'поддержива':5 'устанавлива':3 (1 row)
  • 9. to_tsquery # SELECT to_tsquery('install | maintain'); 'instal' | 'maintain' (1 row) # SELECT to_tsquery('russian', 'устанавливать & поддерживать'); 'устанавлива' & 'поддержива' (1 row)
  • 10. plainto_tsquery & phraseto_tsquery # SELECT plainto_tsquery('install maintain'); 'instal' & 'maintain' (1 row) # SELECT phraseto_tsquery('russian', 'устанавливать поддерживать'); 'устанавлива' <-> 'поддержива' (1 row)
  • 11. tsvector @@ tsquery # SELECT to_tsvector('No need to install and maintain anything except PostgreSQL') @@ plainto_tsquery('install maintain') AS match; match ------- t
  • 12. Indexes: GIN or GiST? GIN vs GiST: ● GIN ○ fast search, not very fast updates ○ better for static data ● GiST ○ slow search, faster updates ○ better for dynamic data If you are not sure use GIN.
  • 13. Practice: 1 / 3 CREATE TABLE IF NOT EXISTS articles(id serial primary key, title varchar(128), content text); -- https://meta.wikimedia.org/wiki/Data_dump_torrents#enwiki -- https://github.com/afiskon/postgresql-fts-example COPY articles FROM PROGRAM 'zcat /path/to/articles.copy.gz';
  • 14. Practice: 2 / 3 CREATE OR REPLACE FUNCTION make_tsvector(title text, content text) RETURNS tsvector AS $$ BEGIN RETURN (setweight(to_tsvector('english', title),'A') || setweight(to_tsvector('english', content), 'B')); END $$ LANGUAGE 'plpgsql' IMMUTABLE;
  • 15. Practice: 3 / 3 CREATE INDEX IF NOT EXISTS idx_fts_articles ON articles USING gin(make_tsvector(title, content)); SELECT id, title FROM articles WHERE make_tsvector(title, content) @@ to_tsquery('bjarne <-> stroustrup'); 2470 | Binary search algorithm 2129 | Bell Labs 2130 | Bjarne Stroustrup 3665 | C (programming language)
  • 16. ts_headline: 1 / 2 SELECT id, ts_headline(title, q) FROM articles, to_tsquery('bjarne <-> stroustrup') AS q -- !!! WHERE make_tsvector(title, content) @@ q; 2470 | Binary search algorithm 2129 | Bell Labs 2130 | <b>Bjarne</b> <b>Stroustrup</b>
  • 17. ts_headline: 2 / 2 SELECT id, ts_headline(title, q, 'StartSel=<em>, StopSel=</em>') -- !!! FROM articles, to_tsquery('bjarne <-> stroustrup') as q WHERE make_tsvector(title, content) @@ q; 2470 | Binary search algorithm 2129 | Bell Labs 2130 | <em>Bjarne</em> <em>Stroustrup</em>
  • 18. ts_rank SELECT id, ts_headline(title, q, 'StartSel=<em>, StopSel=</em>') FROM articles, to_tsquery('bjarne <-> stroustrup') as q WHERE make_tsvector(title, content) @@ q ORDER BY ts_rank(make_tsvector(title, content), q) DESC; 2130 | <em>Bjarne</em> <em>Stroustrup</em> 3665 | C (programming language) 6266 | Edsger W. Dijkstra
  • 19. RUM $ git clone [email protected]:postgrespro/rum.git $ cd rum $ USE_PGXS=1 make install $ USE_PGXS=1 make installcheck psql> CREATE EXTENSION rum;
  • 20. Fuzzy Full Text Search
  • 21. pg_trgm: 1 / 4 create extension pg_trgm; create index articles_trgm_idx on articles using gin (title gin_trgm_ops);
  • 22. pg_trgm: 2 / 4 select show_trgm(title) from articles limit 3; show_trgm | {" a"," ac",acc,ble,cce,ces,com,eco,ess,ibl,ing,lec,mpu,... show_trgm | {" a"," an",ana,arc,chi,his,ism,nar,rch,"sm "} show_trgm | {" a"," af",afg,anh,ani,fgh,gha,han,his,ist,nhi,nis,ory,...
  • 23. pg_trgm: 3 / 4 select title, similarity(title, 'Straustrup') from articles where title % 'Straustrup'; -[ RECORD 1 ]----------------- title | Bjarne Stroustrup similarity | 0.35
  • 24. pg_trgm: 4 / 4 psql> select show_limit(); -[ RECORD 1 ]--- show_limit | 0.3 psql> select set_limit(0.4); -[ RECORD 1 ]-- set_limit | 0.4
  • 25. pg_trgm: like / ilike queries # explain select title from articles where title LIKE '%Stroustrup%'; QUERY PLAN --------------------------------------------------------------------------------- Bitmap Heap Scan on articles (cost=60.02..71.40 rows=3 width=16) Recheck Cond: ((title)::text ~~ '%Stroustrup%'::text) -> Bitmap Index Scan on articles_trgm_idx (cost=0.00..60.02 rows=3... Index Cond: ((title)::text ~~ '%Stroustrup%'::text)
  • 26. pg_trgm: regular expressions # explain select title from articles where title ~* 'Stroustrup'; QUERY PLAN --------------------------------------------------------------------------------- Bitmap Heap Scan on articles (cost=60.02..71.40 rows=3 width=16) Recheck Cond: ((title)::text ~* 'Stroustrup'::text) -> Bitmap Index Scan on articles_trgm_idx (cost=0.00..60.02 rows=3... Index Cond: ((title)::text ~* 'Stroustrup'::text)
  • 27. See also ● The pg_trgm module provides functions and operators for determining the similarity of alphanumeric text based on trigram matching ○ https://www.postgresql.org/docs/current/static/pgtrgm.html ● Full Text Search support for JSON and JSONB ○ https://www.depesz.com/2017/04/04/waiting-for-postgresql-10-full-text-search-support-for-json -and-jsonb/ ● RUM access method ○ https://github.com/postgrespro/rum
  • 28. Thank you for your attention! ● http://eax.me/ ● http://devzen.ru/
  • 30. GIN & arrays create table vec_test(id serial primary key, tags int[]); create index vec_test_gin on vec_test using gin(tags); insert into vec_test (tags) values ('{111,222,333}'); select * from vec_test where '{111}' <@ tags; select * from vec_test where '{111}' @> tags; select * from vec_test where '{111}' = tags; -- intersection is not empty select * from vec_test where '{111}' && tags;