Skip to main content

11 - Real Estate Listing Search: Full-Text with PostgreSQL

Italian full-text search in PostgreSQL: unaccent, stemming, a GIN index, typos with pg_trgm and ranking, measured on 200,000 declared synthetic listings.

What do you think about this article?

11 - Real Estate Listing Search: Full-Text with PostgreSQL
PropTechfedericocalo.dev

At a Glance

Italian full-text search in PostgreSQL: unaccent, stemming, a GIN index, typos with pg_trgm and ranking, measured on 200,000 declared synthetic listings.

"Bilocali universita" does not find "Bilocale ... università": do you need another engine?

A user types «bilocali universita» into the search box of your portal. The listings they need are called «Bilocale ristrutturato vicino all'università» (Italian for "renovated two-room flat near the university"): singular, with the accented letter. A search written with ILIKE '%bilocali%universita%' finds not a single one, and the first reaction is to add a separate search engine with its own infrastructure. For a catalogue that runs from a few tens of thousands to a few million listings, PostgreSQL already knows how to do what you need: reduce words to their stem, ignore accents, tolerate a typo and return the results in a sensible order, all with a GIN index that holds up under load.

This article shows it on two hundred thousand synthetic listings, and also says where the demonstration ends. It does not compare performance with Elasticsearch, which I did not run: it compares only its features, based on its documentation. The timings come from a 16-core machine, from a single run or the best of five, and are there to show the order of magnitude, not to promise a result. For searching by position rather than by text there is the article on PostGIS; here the position appears only once, at the end, to combine the two criteria. The listing texts stay in Italian on purpose, because the point is Italian full-text search; I gloss the words that matter.

The test corpus and the first obstacle: unaccent is not immutable

The schema follows the annuncio table ("listing") described in the article on the platform architecture, with two text fields and a position. The values come from template phrases: seven property types, seven attributes, seven places, seven towns and four description formulas, combined at random with a fixed seed. The vocabulary is tiny on purpose, because that lets me count the expected results, but it has a consequence I come back to later: real text has thousands of distinct words, and the index sizes below are much smaller than the ones you will find on your own data.

200,000 synthetic listings with a small vocabulary and a fixed seed
SET client_min_messages = warning;
CREATE EXTENSION IF NOT EXISTS postgis;
CREATE EXTENSION IF NOT EXISTS unaccent;
CREATE EXTENSION IF NOT EXISTS pg_trgm;
DROP TABLE IF EXISTS annuncio;
CREATE TABLE annuncio (
  id          serial PRIMARY KEY,
  comune      text NOT NULL,
  titolo      text NOT NULL,
  descrizione text NOT NULL,
  posizione   geography(Point, 4326) NOT NULL
);

-- 200,000 SYNTHETIC listings: template phrases and a small vocabulary, fixed seed.
-- The texts stay in Italian on purpose: the article is about Italian full-text search.
SELECT setseed(0.42) AS seed \gset
INSERT INTO annuncio (comune, titolo, descrizione, posizione)
SELECT c, t || ' ' || a || ' ' || l,
       format(d, v),
       ST_SetSRID(ST_MakePoint(18.0 + random() * 0.4, 40.2 + random() * 0.3), 4326)::geography
FROM (
  SELECT (ARRAY['Lecce','Brindisi','Taranto','Otranto','Gallipoli','Nardò','Maglie'])[1 + floor(random()*7)::int] AS c,
         (ARRAY['Monolocale','Bilocale','Trilocale','Quadrilocale','Attico','Villa','Appartamento'])[1 + floor(random()*7)::int] AS t,
         (ARRAY['ristrutturato','luminoso','arredato','con terrazzo','con box auto','al primo piano','con giardino'])[1 + floor(random()*7)::int] AS a,
         (ARRAY['vicino all''università','in centro storico','vicino alla stazione','vicino all''ospedale','a due passi dal mare','in zona residenziale','vicino al parco'])[1 + floor(random()*7)::int] AS l,
         (ARRAY['Immobile composto da %s vani, con cucina abitabile e bagni finestrati. Adatto a studenti e famiglie.',
                'Casa di %s vani in un palazzo tranquillo, con ingresso indipendente e ottime finiture.',
                'Appartamento di %s vani con riscaldamento autonomo, cantina e posto auto condominiale.',
                'Soluzione di %s vani già libera, vicina ai servizi e ai collegamenti pubblici.'])[1 + floor(random()*4)::int] AS d,
         (1 + floor(random()*6)::int)::text AS v
  FROM generate_series(1, 200000)
) s;
ANALYZE annuncio;

SELECT count(*) AS listings, pg_size_pretty(pg_table_size('annuncio')) AS table_size FROM annuncio;
SELECT id, titolo FROM annuncio WHERE id IN (1, 2, 3) ORDER BY id;

-- Output:
--  listings | table_size
-- ----------+------------
--    200000 | 39 MB
-- (1 row)
--
--  id |                     titolo
-- ----+-------------------------------------------------
--   1 | Trilocale con giardino vicino all'università
--   2 | Villa con terrazzo vicino al parco
--   3 | Appartamento ristrutturato in zona residenziale
-- (3 rows)

The listing creates the three extensions used throughout the article (postgis, unaccent, pg_trgm), the table, and fills it with a single INSERT ... SELECT on top of generate_series. The setseed(0.42) line makes the experiment repeatable: the random() function always starts from the same point. The output confirms 200,000 rows and 39 MB of table, and shows what the first titles look like: property type, attribute and place joined together, with the accent of «università» ("university") in its place.

The error you meet on your first generated column

The PostgreSQL documentation suggests keeping the search vector in a stored generated column, so that it updates by itself whenever the text changes. The natural attempt is to put unaccent(titolo) inside the expression, and it fails with «generation expression is not immutable»: the unaccent function is declared stable (provolatile = 's' in pg_proc, read on the test cluster), because it relies on a dictionary that can be modified, and a generated column accepts only immutable functions. The output of the listing below shows exactly that message on its first line.

The obvious attempt with unaccent() fails; the search configuration works
\set ON_ERROR_STOP off
-- First attempt, the obvious one: unaccent() inside the generated column.
ALTER TABLE annuncio ADD COLUMN ricerca_prova tsvector
  GENERATED ALWAYS AS (to_tsvector('italian', unaccent(titolo))) STORED;

\set ON_ERROR_STOP on
SET client_min_messages = warning;
-- Fix: a search configuration that strips accents INSIDE the parser pipeline.
DROP TEXT SEARCH CONFIGURATION IF EXISTS it_unaccent;
CREATE TEXT SEARCH CONFIGURATION it_unaccent (COPY = italian);
ALTER TEXT SEARCH CONFIGURATION it_unaccent
  ALTER MAPPING FOR hword, hword_part, word WITH unaccent, italian_stem;

SELECT to_tsvector('it_unaccent', 'Bilocali vicino all''università') AS vector,
       websearch_to_tsquery('it_unaccent', 'bilocale universita') AS query;

\timing on
ALTER TABLE annuncio ADD COLUMN ricerca tsvector
  GENERATED ALWAYS AS (
    setweight(to_tsvector('it_unaccent', titolo), 'A') ||
    setweight(to_tsvector('it_unaccent', descrizione), 'B')
  ) STORED;
\timing off
ANALYZE annuncio;
SELECT pg_size_pretty(pg_table_size('annuncio')) AS table_with_column;

-- Output:
-- psql:02_config.sql:4: ERROR:  generation expression is not immutable
--               vector               |         query
-- -----------------------------------+-----------------------
--  'bilocal':1 'univers':4 'vicin':2 | 'bilocal' & 'univers'
-- (1 row)
--
-- Time: 3456.192 ms (00:03.456)
--  table_with_column
-- -------------------
--  80 MB
-- (1 row)

The route indicated by the unaccent documentation itself is to put the dictionary inside a search configuration. The line CREATE TEXT SEARCH CONFIGURATION it_unaccent (COPY = italian) starts from the Italian configuration, and ALTER MAPPING FOR hword, hword_part, word WITH unaccent, italian_stem tells it to pass every word first through the dictionary that strips accents and then through the stemmer. The alternative I discarded is an SQL function that wraps unaccent and declares it IMMUTABLE: it works, but it lies to the planner, and if one day you change the dictionary rules the indexes already built silently stay inconsistent. The configuration has another advantage: the same treatment applies to documents and to queries, because you apply it by giving the name of the configuration.

The output shows the result. «Bilocali vicino all'università» becomes the vector 'bilocal':1 'univers':4 'vicin':2: three stems with the position of each, while «all'» ("to the") was dropped as a stop word. The query «bilocale universita», without the accent, produces 'bilocal' & 'univers', so the two meet in the middle. The ricerca column then took a few seconds to compute (the time changes on every run) and took the table from 39 to 80 MB: a stored vector costs space, and that is the price of not recomputing it at every search. The two weights ('A' for the title, 'B' for the description) are there for ordering, and I come back to them in the section on ranking.

Searching in different ways and getting the same result

With the column ready you search with ricerca @@ websearch_to_tsquery('it_unaccent', '...'). I chose websearch_to_tsquery among the four functions that turn a string into a query because it accepts what a user types without syntax errors: quotes for a phrase, the minus sign to exclude, or for the alternative. The documentation says that to_tsquery offers more functions but is less forgiving with input, and that plainto_tsquery knows neither phrases nor exclusions. The listing tries four spellings of the same search, the same search with ILIKE, and the advanced search syntax.

The same words written in different ways, the comparison with ILIKE and the websearch_to_tsquery syntax
-- The same words written in different ways: they must return the same number of rows.
SELECT q AS searched,
       (SELECT count(*) FROM annuncio WHERE ricerca @@ websearch_to_tsquery('it_unaccent', q)) AS found
FROM (VALUES ('bilocale università'), ('bilocali universita'), ('BILOCALI Università'), ('bilocale vicino università')) AS t(q);

-- The comparison with ILIKE, which is what you write before knowing full-text search.
SELECT count(*) AS ilike_bilocali_universita
FROM annuncio WHERE titolo ILIKE '%bilocali%universita%';
SELECT count(*) AS ilike_bilocale_università
FROM annuncio WHERE titolo ILIKE '%bilocale%università%';

-- websearch syntax: quotes for a phrase, minus to exclude, or for the alternative.
SELECT q AS searched,
       websearch_to_tsquery('it_unaccent', q) AS tsquery,
       (SELECT count(*) FROM annuncio WHERE ricerca @@ websearch_to_tsquery('it_unaccent', q)) AS found
FROM (VALUES ('bilocale giardino'),
             ('bilocale -giardino università'),
             ('"bilocale con giardino"'),
             ('attico or villa mare')) AS t(q);

-- Output:
--           searched          | found
-- ----------------------------+-------
--  bilocale università        |  4084
--  bilocali universita        |  4084
--  BILOCALI Università        |  4084
--  bilocale vicino università |  4084
-- (4 rows)
--
--  ilike_bilocali_universita
-- ---------------------------
--                          0
-- (1 row)
--
--  ilike_bilocale_università
-- ---------------------------
--                       4084
-- (1 row)
--
--            searched            |              tsquery               | found
-- -------------------------------+------------------------------------+-------
--  bilocale giardino             | 'bilocal' & 'giardin'              |  4156
--  bilocale -giardino università | 'bilocal' & !'giardin' & 'univers' |  3435
--  "bilocale con giardino"       | 'bilocal' <2> 'giardin'            |  4156
--  attico or villa mare          | 'attic' | 'vill' & 'mar'           | 32683
-- (4 rows)

The four spellings, capitals, singular, plural, missing accent, all return 4,084 listings. «bilocale vicino università» returns the same number only because in my data every title with «università» also contains «vicino» ("near"): on real data it would not be so, and it is better not to confuse an outcome of this corpus with a property of the function. ILIKE with «bilocali» and «universita» finds zero rows, and fails for two reasons at once (the plural and the accent); with the words written exactly as in the text it finds 4,084, the same number, but the leading wildcard of '%bilocale%' rules out an ordinary B-tree index.

The third table contains the subtlest trap. The string «attico or villa mare» ("penthouse or villa sea") produces 'attic' | 'vill' & 'mar', that is «penthouse, or villa and sea»: the & operator binds tighter than |, as in algebra. Whoever types those words probably meant "penthouse or villa, either way near the sea", and the result is 32,683 listings, almost all the penthouses in the catalogue, sea or not. If you expose the advanced syntax to your users, write it in the help of the box; if you do not expose it, build the query yourself instead of leaving it to be interpreted by the function.

The GIN index: what it saves and when it matters

A GIN index (Generalized Inverted Index) is an inverted index: for each stem it keeps the list of the rows that contain it. A search for «attico, giardino, università» ("penthouse, garden, university") consults three lists and intersects them, instead of reading the whole table. The listing runs EXPLAIN (ANALYZE, BUFFERS) on the same query before and after creating the index, and then on a very weakly selective query, «bilocale», as a reminder that the index is no miracle when the answer is a large slice of the table.

EXPLAIN (ANALYZE, BUFFERS) of the same search without and with the GIN index
SET client_min_messages = warning;
-- Selective query: attico + giardino + università.
\echo '--- without index'
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF)
SELECT id FROM annuncio
WHERE ricerca @@ websearch_to_tsquery('it_unaccent', 'attico giardino università');

\timing on
CREATE INDEX annuncio_ricerca_gin ON annuncio USING gin (ricerca);
\timing off
ANALYZE annuncio;
SELECT pg_size_pretty(pg_relation_size('annuncio_ricerca_gin')) AS gin_index;

\echo '--- with index'
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF)
SELECT id FROM annuncio
WHERE ricerca @@ websearch_to_tsquery('it_unaccent', 'attico giardino università');

\echo '--- weakly selective query: bilocale (about 1/7 of the listings)'
EXPLAIN (ANALYZE, COSTS OFF, BUFFERS)
SELECT id FROM annuncio
WHERE ricerca @@ websearch_to_tsquery('it_unaccent', 'bilocale');

-- Output:
-- --- without index
--                                     QUERY PLAN
-- ----------------------------------------------------------------------------------
--  Gather (actual time=0.586..19.949 rows=570 loops=1)
--    Workers Planned: 2
--    Workers Launched: 2
--    Buffers: shared hit=2624 read=7552
--    ->  Parallel Seq Scan on annuncio (actual time=0.232..14.417 rows=190 loops=3)
--          Filter: (ricerca @@ '''attic'' & ''giardin'' & ''univers'''::tsquery)
--          Rows Removed by Filter: 66477
--          Buffers: shared hit=2624 read=7552
--  Planning:
--    Buffers: shared hit=89
--  Planning Time: 1.715 ms
--  Execution Time: 20.007 ms
-- (12 rows)
--
-- Time: 439.452 ms
--  gin_index
-- -----------
--  4080 kB
-- (1 row)
--
-- --- with index
--                                          QUERY PLAN
-- ---------------------------------------------------------------------------------------------
--  Bitmap Heap Scan on annuncio (actual time=3.286..5.957 rows=570 loops=1)
--    Recheck Cond: (ricerca @@ '''attic'' & ''giardin'' & ''univers'''::tsquery)
--    Heap Blocks: exact=554
--    Buffers: shared hit=169 read=415
--    ->  Bitmap Index Scan on annuncio_ricerca_gin (actual time=3.221..3.221 rows=570 loops=1)
--          Index Cond: (ricerca @@ '''attic'' & ''giardin'' & ''univers'''::tsquery)
--          Buffers: shared hit=30
--  Planning:
--    Buffers: shared hit=17
--  Planning Time: 0.127 ms
--  Execution Time: 5.993 ms
-- (11 rows)
--
-- --- weakly selective query: bilocale (about 1/7 of the listings)
--                                           QUERY PLAN
-- -----------------------------------------------------------------------------------------------
--  Bitmap Heap Scan on annuncio (actual time=3.320..53.241 rows=28515 loops=1)
--    Recheck Cond: (ricerca @@ '''bilocal'''::tsquery)
--    Heap Blocks: exact=9651
--    Buffers: shared hit=3240 read=6419
--    ->  Bitmap Index Scan on annuncio_ricerca_gin (actual time=2.223..2.223 rows=28515 loops=1)
--          Index Cond: (ricerca @@ '''bilocal'''::tsquery)
--          Buffers: shared hit=8
--  Planning:
--    Buffers: shared hit=1
--  Planning Time: 0.070 ms
--  Execution Time: 54.256 ms
-- (11 rows)

Without the index, the plan is a Parallel Seq Scan with two workers: it discards 66,477 rows in each of the three processes, keeps 570, and takes a couple of tens of milliseconds. With the index the plan becomes a Bitmap Index Scan followed by a Bitmap Heap Scan: the index consults 30 buffers, and execution drops to a few milliseconds. The index weighs 4,080 kB, about one twentieth of the table's 80 MB, but in a real corpus with tens of thousands of distinct stems it would be much larger. The third plan answers the question "does the index always save me?": «bilocale» matches 28,515 rows and execution climbs to tens of milliseconds, because the real work is reading 9,651 pages of the table to extract the rows, not searching the index.

From how many listings on a sequential scan is not enough

The question in the title of this article has an answer that depends on your load, but the trend can be measured. The listing builds a test table with the same vectors repeated up to 10,000, 50,000, 200,000 and one million rows, empties the pending list of the GIN index with gin_clean_pending_list (otherwise a freshly filled index looks slower than it is), and measures the selective search with and without the index, taking the best of five runs with a warm cache.

Time of a selective search as rows grow, with a sequential scan and with GIN
SET client_min_messages = warning;
-- Run EXPLAIN ANALYZE and return the time, in milliseconds.
CREATE OR REPLACE FUNCTION tempo_ms(q text) RETURNS numeric LANGUAGE plpgsql AS $$
DECLARE j json;
BEGIN
  EXECUTE 'EXPLAIN (ANALYZE, FORMAT JSON) ' || q INTO j;
  RETURN round(((j->0->>'Execution Time')::numeric), 1);
END $$;

-- Copies of the same set of texts at growing sizes (rows repeat: this is a timing test, not a relevance test).
DROP TABLE IF EXISTS prova;
CREATE TABLE prova AS SELECT ricerca FROM annuncio WHERE false;
CREATE INDEX prova_gin ON prova USING gin (ricerca);

CREATE TEMP TABLE esiti (rows_count int, without_index_ms numeric, with_index_ms numeric);
DO $$
DECLARE n int; q text := $q$SELECT 1 FROM prova WHERE ricerca @@ websearch_to_tsquery('it_unaccent', 'attico giardino università')$q$;
        a numeric; b numeric;
BEGIN
  FOREACH n IN ARRAY ARRAY[10000, 50000, 200000, 1000000] LOOP
    TRUNCATE prova;
    INSERT INTO prova SELECT ricerca FROM annuncio, generate_series(1, ceil(n / 200000.0)::int) LIMIT n;
    PERFORM gin_clean_pending_list('prova_gin');   -- empties the GIN pending list
    ANALYZE prova;
    PERFORM tempo_ms(q);                        -- warm-up
    SET LOCAL enable_bitmapscan = off; SET LOCAL enable_indexscan = off;
    SELECT min(tempo_ms(q)) INTO a FROM generate_series(1, 5);   -- best of 5
    RESET enable_bitmapscan; RESET enable_indexscan;
    SELECT min(tempo_ms(q)) INTO b FROM generate_series(1, 5);
    INSERT INTO esiti VALUES (n, a, b);
  END LOOP;
END $$;
SELECT * FROM esiti ORDER BY rows_count;

-- Output:
--  rows_count | without_index_ms | with_index_ms
-- ------------+------------------+---------------
--       10000 |              1.4 |           0.2
--       50000 |              7.5 |           0.8
--      200000 |             18.6 |           3.5
--     1000000 |             50.0 |          11.9
-- (4 rows)

Times grow roughly linearly with the sequential scan and much more gently with the index: from about 1-2 ms against 0.2 ms at ten thousand rows, up to 50-70 ms against 12-15 ms at a million. The ratio sits between 4 and 9 times or so, and the absolute numbers are small: on this machine, with the parallel scan, a million listings are scanned in less than a tenth of a second. Two caveats keep you from reading them as a verdict. The parallel plan occupies three processes: with a hundred simultaneous searches the workers fight over the cores and the advantage vanishes. And the repeated rows make the test an exercise about time and not about relevance. The practical rule I draw from it is this: below ten thousand listings the index changes nothing the user can perceive; from a few hundred thousand on, or with many concurrent searches, you want it.

Typo tolerance with trigrams

Full-text reasons on whole words reduced to their stem, and a typo is not a word: «Leccee» has no stem in common with «Lecce» (the Salento city). The pg_trgm extension breaks a string into triples of consecutive characters (the trigrams) and measures how many two strings share. The value runs from 0 to 1 and the % operator is true when it exceeds the pg_trgm.similarity_threshold threshold, whose default value is 0.3 according to the documentation.

The typo "Leccee": full-text does not see it, pg_trgm does
SET client_min_messages = warning;
-- 'Leccee' with a double e: full-text finds nothing, because the typo is not a word.
SELECT count(*) AS full_text_leccee
FROM annuncio WHERE to_tsvector('it_unaccent', comune) @@ websearch_to_tsquery('it_unaccent', 'Leccee');

CREATE INDEX annuncio_comune_trgm ON annuncio USING gin (comune gin_trgm_ops);
ANALYZE annuncio;

SHOW pg_trgm.similarity_threshold;
SELECT count(*) AS threshold_03 FROM annuncio WHERE comune % 'Leccee';
SET pg_trgm.similarity_threshold = 0.7;
SELECT count(*) AS threshold_07 FROM annuncio WHERE comune % 'Leccee';
RESET pg_trgm.similarity_threshold;

-- Better still: correct against a small dictionary of place names and pass the corrected word to full-text.
CREATE TABLE IF NOT EXISTS comune_noto AS SELECT DISTINCT comune FROM annuncio;
CREATE INDEX IF NOT EXISTS comune_noto_trgm ON comune_noto USING gin (comune gin_trgm_ops);
SELECT q, (SELECT comune FROM comune_noto WHERE comune % q ORDER BY comune <-> q LIMIT 1) AS did_you_mean,
       round(similarity((SELECT comune FROM comune_noto ORDER BY comune <-> q LIMIT 1), q)::numeric, 3) AS similarity
FROM (VALUES ('Leccee'), ('Galipoli'), ('Brindsi'), ('Roma')) AS t(q);

-- Output:
--  full_text_leccee
-- ------------------
--                 0
-- (1 row)
--
--  pg_trgm.similarity_threshold
-- ------------------------------
--  0.3
-- (1 row)
--
--  threshold_03
-- --------------
--         28747
-- (1 row)
--
--  threshold_07
-- --------------
--             0
-- (1 row)
--
--     q     | did_you_mean | similarity
-- ----------+--------------+------------
--  Leccee   | Lecce        |      0.625
--  Galipoli | Gallipoli    |      0.727
--  Brindsi  | Brindisi     |      0.545
--  Roma     |              |      0.000
-- (4 rows)

The first line of the output says that full-text, given «Leccee», finds nothing. Then the similarity between «Lecce» and «Leccee» is 0.625, and at threshold 0.3 the % operator finds all 28,747 listings in Lecce (it finds none in other towns, because the others have zero similarity). Raising the threshold to 0.7 takes the result down to zero: there is no right threshold in absolute terms, and a value that is too high rejects real typos, one that is too low lets through words that have nothing to do with it. The last table shows the way I prefer to use the tool: instead of indexing the whole catalogue column with a trigram index, I apply it to a small table of known place names (comune_noto) and use the result to say "did you mean Lecce". «Brindsi» reaches 0.545 and is corrected to «Brindisi»; «Roma» resembles nothing and proposes nothing. The suggestion then goes to full-text, which works on the right word.

What order the results come in: ts_rank_cd and its limits

A search that finds 4,000 listings has to put some of them at the top. PostgreSQL offers ts_rank, which counts the frequency of the stems, and ts_rank_cd, which computes the cover density and takes into account how close the searched terms are to each other. The listing uses the second on «attico giardino» ("penthouse garden"), with and without normalization for text length, counts how many listings share the top score and, in the last query, shows what the weights do.

Ordering with ts_rank_cd, and what the weights do
SET client_min_messages = warning;
-- The title weighs more than the description (weights A and B set in the generated column). Normalization 1: divides by 1 + log(length).
SELECT id, titolo,
       round(ts_rank_cd(ricerca, q)::numeric, 4)    AS rank_cd,
       round(ts_rank_cd(ricerca, q, 1)::numeric, 4) AS rank_cd_norm1
FROM annuncio, websearch_to_tsquery('it_unaccent', 'attico giardino') AS q
WHERE ricerca @@ q
ORDER BY ts_rank_cd(ricerca, q, 1) DESC, id
LIMIT 5;

-- How many rows share the top score: the synthetic data repeats the same phrases.
SELECT round(ts_rank_cd(ricerca, q, 1)::numeric, 4) AS score, count(*) AS listings
FROM annuncio, websearch_to_tsquery('it_unaccent', 'attico giardino') AS q
WHERE ricerca @@ q
GROUP BY 1 ORDER BY 1 DESC LIMIT 3;

-- The same terms in the title versus the description alone: 'giardino' in A, and the same word in B and in D.
SELECT ts_rank_cd(setweight(to_tsvector('it_unaccent', 'Villa con giardino'), 'A'), q)  AS in_title,
       ts_rank_cd(setweight(to_tsvector('it_unaccent', 'Villa con giardino'), 'B'), q)  AS in_description,
       ts_rank_cd(setweight(to_tsvector('it_unaccent', 'Villa con giardino'), 'D'), q)  AS weight_d
FROM websearch_to_tsquery('it_unaccent', 'giardino') AS q;

-- Output:
--  id  |                  titolo                  | rank_cd | rank_cd_norm1
-- -----+------------------------------------------+---------+---------------
--   19 | Attico con giardino vicino al parco      |  0.5000 |        0.1895
--  119 | Attico con giardino vicino all'ospedale  |  0.5000 |        0.1895
--  497 | Attico con giardino in centro storico    |  0.5000 |        0.1895
--  694 | Attico con giardino in zona residenziale |  0.5000 |        0.1895
--  946 | Attico con giardino vicino alla stazione |  0.5000 |        0.1895
-- (5 rows)
--
--  score  | listings
-- --------+----------
--  0.1895 |     2634
--  0.1846 |      412
--  0.1803 |      872
-- (3 rows)
--
--  in_title | in_description | weight_d
-- ----------+----------------+----------
--         1 |            0.4 |      0.1
-- (1 row)

The first five results are «Attico con giardino ...» ("penthouse with garden ..."), all with 0.5 and, normalized, 0.1895; the second table explains why: 2,634 listings have the same top score, because in my corpus the phrases repeat. On real data the scores spread out better, but it is always worth adding a deterministic secondary criterion (here the id) so that the order does not change between two requests. The last row shows the effect of the weights: the same word is worth 1 if it appears in the title (weight A), 0.4 in the description (B), 0.1 with weight D. These are the default values and you can pass your own array as the first argument.

The limit to know about is stated by the documentation: the ranking functions "do not use global information". The score of a listing depends only on that listing and the query, not on how rare a word is across the whole catalogue. The BM25 algorithm, which Elasticsearch and Lucene use by default according to their documentation, instead weighs the rarity of terms in the corpus: «giardino» ("garden") weighs more than «vicino» ("near") if it appears in fewer listings. If you need this, or if you want to add a search by meaning alongside words, the article on hybrid retrieval with BM25 and vectors is the next step.

Text and position in the same query

The typical case for a portal is "a penthouse with a garden less than five kilometres from the centre". These are two conditions on two different indexes: GIN for the text, GiST for the position, the type of index that the article on PostGIS explains. The listing creates the spatial index, asks the planner how to combine them, and compares the result with the two conditions taken alone.

Text and radius in the same query: two indexes combined with BitmapAnd
SET client_min_messages = warning;
CREATE INDEX annuncio_posizione_gist ON annuncio USING gist (posizione);
ANALYZE annuncio;

-- Text + position in the same query: 'attico giardino' within 5 km of the centre of Lecce.
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT id FROM annuncio
WHERE ricerca @@ websearch_to_tsquery('it_unaccent', 'attico giardino')
  AND ST_DWithin(posizione, ST_SetSRID(ST_MakePoint(18.1720, 40.3515), 4326)::geography, 5000);

SELECT count(*) AS text_and_radius,
       (SELECT count(*) FROM annuncio WHERE ricerca @@ websearch_to_tsquery('it_unaccent', 'attico giardino')) AS text_only,
       (SELECT count(*) FROM annuncio WHERE ST_DWithin(posizione, ST_SetSRID(ST_MakePoint(18.1720, 40.3515), 4326)::geography, 5000)) AS radius_only
FROM annuncio
WHERE ricerca @@ websearch_to_tsquery('it_unaccent', 'attico giardino')
  AND ST_DWithin(posizione, ST_SetSRID(ST_MakePoint(18.1720, 40.3515), 4326)::geography, 5000);

-- Output:
--                                                                    QUERY PLAN
-- ------------------------------------------------------------------------------------------------------------------------------------------------
--  Bitmap Heap Scan on annuncio (actual rows=251 loops=1)
--    Recheck Cond: (ricerca @@ '''attic'' & ''giardin'''::tsquery)
--    Filter: st_dwithin(posizione, '0101000020E610000079E92631082C3240A245B6F3FD2C4440'::geography, '5000'::double precision, true)
--    Rows Removed by Filter: 185
--    Heap Blocks: exact=426
--    ->  BitmapAnd (actual rows=0 loops=1)
--          ->  Bitmap Index Scan on annuncio_ricerca_gin (actual rows=4042 loops=1)
--                Index Cond: (ricerca @@ '''attic'' & ''giardin'''::tsquery)
--          ->  Bitmap Index Scan on annuncio_posizione_gist (actual rows=23697 loops=1)
--                Index Cond: (posizione && _st_expand('0101000020E610000079E92631082C3240A245B6F3FD2C4440'::geography, '5000'::double precision))
-- (10 rows)
--
--  text_and_radius | text_only | radius_only
-- -----------------+-----------+-------------
--              251 |      4042 |       13799
-- (1 row)

The plan uses the two indexes together: a BitmapAnd intersects the two bit maps, the text one (4,042 rows) and the one for the box around the point (23,697), and the exact st_dwithin filter discards 185 of the 436 rows left to keep the right 251. The last result confirms it: 251 listings satisfy both conditions, against 4,042 for the text alone and 13,799 for the radius alone. The planner makes this choice based on statistics; if your data is distributed differently, it may choose to use only one index and filter with the other. Check the plan, do not take it for granted.

Where a dedicated engine wins

I have shown what is executable with PostgreSQL. On Elasticsearch, as its documentation describes it, there are features that are missing here or require work on your part. I listed them with no numerical comparison.

  • Facets: Elasticsearch documents aggregations as a feature of its own (groupings by category and metrics); in PostgreSQL you write them with GROUP BY on the result, and the cost grows with the rows found.
  • Scoring on rarity: BM25 is the default, whereas ts_rank_cd is not, as seen.
  • Synonyms: PostgreSQL has synonym and thesaurus dictionaries, but you write and maintain the files yourself.

The list is a decision criterion, not a list of shortcomings: if facets are the heart of the experience, or if the corpus grows beyond what a single node can hold (a threshold I did not measure here), adding the dedicated engine makes sense. If instead you search text, a bit of typo tolerance and a filter by position, all in a catalogue of normal size, having a single database to maintain, with the transactions you already use to write the listing, is a concrete saving in complexity.

Where this fits in the series

Article 1 defines the listing and its pagination; the text search of this article is its natural extension. Article 8 covers the search by position that appears here in the last example. A second way of grouping listings by area is in the twelfth article, the one on H3 cells.

Previous in the series: 10. PropTech Compliance: Fair Housing and Algorithmic Bias. Next in the series: 12. H3 Geographic Indexing for the Real Estate Market.

What you can do now

You can build an Italian text search on PostgreSQL that ignores accents, capitals and plurals, and you know why you need a search configuration and not an unaccent() in the generated column. You can read an EXPLAIN (ANALYZE) to see whether the GIN index is working and when it is not enough, add a typo suggestion with pg_trgm, and combine text and radius in the same query. And you can tell a colleague precisely what PostgreSQL does not do, scoring on rarity and facets, before deciding whether you need another engine.

Sources

The eight listings were run on 2026-11-12 with PostgreSQL 17.10, PostGIS 3.5 and pg_trgm on a temporary cluster, with the comments and labels in English (the output shown is the one from that run). The listings are synthetic, generated with a fixed seed; the timings come from a 16-core test machine and vary with every run. Elasticsearch was not run: no number concerns it.

Try These Tools

Free developer tools related to this topic.

Commenti

Caricamento commenti...

Sign in to comment

New articles and tools on Telegram too

The Telegram channel flags the site's new articles and tools.

Did you like this article?

Explore other content on the blog or discover my projects