Location-aware search is one of the most useful features of modern applications. A user who searches for “coffee” expects coffee shops near them without typing a location, and they expect the results instantly.

Postgres can handle this without any extra infrastructure. The PostGIS extension handles location, and full-text search handles the words. The difficult part is the query plan. The same SQL can take 0.2 ms or 36 ms, and the only difference is the word that the user typed.

In this guide, we’ll set up PostGIS and full-text search, write radius and nearest-neighbor queries that use your indexes, and see why rare words slow those queries down. We’ll fix the problem with a multicolumn GiST index, and then look at how purpose-built search engines approach the same problem.

Note

The examples use Postgres 17 and PostGIS 3.5. The three-argument ST_Point(lon, lat, srid) used throughout needs PostGIS 3.2 or later. The Typesense examples use Typesense 30.1. Timings are EXPLAIN ANALYZE execution times: the median of seven runs in one warm connection, with SET jit = off;, in Docker on an Apple M5 Pro. Your numbers will differ, but the comparisons should hold.

Start a PostGIS container. The official postgis/postgis:17-3.5 image has no ARM build, so on Apple Silicon use the multi-arch community image:

docker run -d \
	--name postgis-lab \
	-e POSTGRES_PASSWORD=postgres \
	-p 5432:5432 \
	imresamu/postgis:17-3.5

Enable the extension:

CREATE EXTENSION IF NOT EXISTS postgis;

Create a places table:

CREATE TABLE places (
	id bigserial PRIMARY KEY,
	name text NOT NULL,
	category text NOT NULL,
	description text,
	geog geography(Point, 4326) NOT NULL,
	search_tsv tsvector GENERATED ALWAYS AS (
		setweight(to_tsvector('english', coalesce(name, '')), 'A') ||
		setweight(to_tsvector('english', coalesce(description, '')), 'B')
	) STORED
);

Two key points about the table:

  • The geog column uses the geography type, which stores longitude and latitude on a model of the Earth’s curved surface and returns distances in meters. It takes two parameters: the shape, such as Point or Polygon, and the SRID (Spatial Reference System Identifier). SRID 4326 is WGS 84, the standard for GPS coordinates.

  • The search_tsv column is a generated tsvector that combines name and description. to_tsvector splits the text into words, drops stop words like “and”, and reduces each word to a stem. setweight makes matches in name count more than matches in description, and coalesce treats a NULL column as an empty string.

Load Sample Data

Next, load some data. The examples in this guide run against 2 million synthetic places spread across five US cities. The word “coffee” appears in about 21% of places in every city, while “pho” is common in Seattle and rare everywhere else. Every query searches around Times Square in New York.

The data comes from a single INSERT that uses generate_series with a fixed random seed, so you’ll get the same rows on Postgres 17. Run it in one psql session. It takes under a minute.

SQL to generate the sample data
SELECT setseed(0.42);

INSERT INTO places (name, category, description, geog)
WITH cities(city_id, city, lon, lat) AS (
	VALUES
		(0, 'New York',      -73.9855, 40.7580),
		(1, 'Seattle',      -122.3321, 47.6062),
		(2, 'San Francisco', -122.4194, 37.7749),
		(3, 'Chicago',       -87.6298, 41.8781),
		(4, 'Austin',        -97.7431, 30.2672)
),
raw AS (
	SELECT
		g % 5 AS city_id,
		random() AS r_word,
		random() AS r_dish,
		random() AS r_adj,
		random() AS r_suffix,
		random() AS r_extra,
		random() AS r_late,
		-- Normal distribution around the city center, so the center is dense
		sqrt(-2 * ln(1 - random())) AS dist,
		2 * pi() * random() AS angle
	FROM generate_series(1, 2000000) AS g
),
picked AS (
	SELECT
		r.*,
		c.city, c.lon, c.lat,
		CASE
			WHEN r.r_word < 0.21 THEN 'coffee'                      -- 21% everywhere
			WHEN r.city_id = 1 AND r.r_word < 0.26 THEN 'pho'       -- 5% in Seattle
			WHEN r.r_word < 0.2105 THEN 'pho'                       -- 0.05% elsewhere
			ELSE (ARRAY['ramen','pizza','tacos','bagels','sushi','burgers','dumplings','barbecue','salads','sandwiches'])[1 + floor(r.r_dish * 10)::int]
		END AS dish
	FROM raw r
	JOIN cities c USING (city_id)
)
SELECT
	(ARRAY['Golden','Blue','Corner','Little','Urban','Old Town','Sunny','Red Door','Lucky','Harbor'])[1 + floor(r_adj * 10)::int]
		|| ' ' || initcap(dish) || ' '
		|| (ARRAY['House','Bar','Kitchen','Spot','Co.'])[1 + floor(r_suffix * 5)::int] AS name,
	CASE WHEN dish = 'coffee' THEN 'cafe' ELSE 'restaurant' END AS category,
	'Serving ' || dish || ' and '
		|| CASE
			WHEN dish = 'ramen' AND r_extra >= 5.0 / 6 THEN 'gyoza'                -- avoid "ramen and ramen"
			ELSE (ARRAY['pastries','tea','desserts','cocktails','snacks','ramen'])[1 + floor(r_extra * 6)::int]
		END
		|| ' in ' || city || '.'
		|| CASE WHEN r_late < 0.2 THEN ' Open late.' WHEN r_late < 0.5 THEN ' Open daily.' ELSE '' END AS description,
	ST_Point(
		lon + 0.04 * dist * cos(angle) / cos(radians(lat)),
		lat + 0.04 * dist * sin(angle),
		4326
	)::geography AS geog
FROM picked;

Create two indexes, and then run VACUUM ANALYZE. Postgres uses the statistics to estimate how many rows will match a query, which helps it choose a plan:

CREATE INDEX places_geog_gist ON places USING gist (geog);
CREATE INDEX places_tsv_gin ON places USING gin (search_tsv);
VACUUM ANALYZE places;

What the indexes do:

  • The location index, places_geog_gist, answers distance questions. This GiST index finds points within a distance, or returns points nearest first.

  • The text index, places_tsv_gin, answers word questions. This GIN (inverted) index finds rows that match a full-text query, but it cannot return rows in any order, so it cannot help with “nearest” or with ranking.

Tip

CREATE INDEX CONCURRENTLY is a better option for production, because it does not block writes to the table. The examples use CREATE INDEX for simplicity.

PostGIS Geography Functions

  1. ST_Point: Creates a point from longitude, latitude, and an SRID.
  2. ST_DWithin: Returns true if two points are within a distance. It can use a spatial index.
  3. ST_Distance: Returns the distance between two points. It cannot use a spatial index.
  4. <->: Returns the distance between two points. In an ORDER BY, it can use a spatial index to return rows nearest first.

ST_DWithin vs ST_Distance: Filter by Radius

Most developers write the first radius query with ST_Distance:

SELECT id, name
FROM places
WHERE ST_Distance(geog, ST_Point(-73.9855, 40.7580, 4326)::geography) <= 2000
	AND search_tsv @@ websearch_to_tsquery('english', 'coffee')
ORDER BY ST_Distance(geog, ST_Point(-73.9855, 40.7580, 4326)::geography)
LIMIT 20;

The query returns the correct rows in ~156 ms, but the plan never uses the location index. ST_Distance returns a number, and Postgres cannot turn “a function result is at most 2000” into an index lookup. Postgres reads all ~420,000 “coffee” rows from the text index and calculates a distance for each row.

Replace the filter with ST_DWithin:

SELECT
	id,
	name,
	ST_Distance(geog, ST_Point(-73.9855, 40.7580, 4326)::geography) AS meters
FROM places
WHERE ST_DWithin(geog, ST_Point(-73.9855, 40.7580, 4326)::geography, 2000)
	AND search_tsv @@ websearch_to_tsquery('english', 'coffee')
ORDER BY meters
LIMIT 20;

You should immediately notice the improvement: the same result now takes ~28 ms instead of ~156 ms. PostGIS rewrites ST_DWithin into a bounding-box check that the location index supports. In this run, Postgres scanned both indexes, combined the two results in a BitmapAnd step, and read only the rows that match both conditions.

Use ST_DWithin to filter, and ST_Distance to show or sort the distance of the rows that remain.

Note

If your table stores locations in a geometry column, do not cast it to geography inside the WHERE filter. The spatial index cannot serve a filter on geom::geography, so Postgres calculates the distance for every text match.

Nearest-Neighbor Search with the <-> Operator

Some searches have no radius. “The 20 closest coffee shops” is one example. For this query, PostGIS provides the <-> distance operator:

SELECT
	id,
	name,
	geog <-> ST_Point(-73.9855, 40.7580, 4326)::geography AS meters
FROM places
WHERE search_tsv @@ websearch_to_tsquery('english', 'coffee')
ORDER BY geog <-> ST_Point(-73.9855, 40.7580, 4326)::geography
LIMIT 20;

This query takes 0.2 ms. When <-> is in the ORDER BY clause, the location index returns rows in order of distance, nearest first. Postgres checks each row against the text condition and stops after 20 matches. For “coffee”, Postgres reads 61 rows out of 2 million.

Why Rare Words Make Nearest-Neighbor Queries Slow

Run the same query for “pho”. The plan does not change, but the query now takes 36 ms:

Limit
  ->  Index Scan using places_geog_gist on places
        Order By: (geog <-> '...'::geography)
        Filter: (search_tsv @@ '''pho'''::tsquery)
        Rows Removed by Filter: 23803

Pho places are rare near Times Square. The index scan moves outward from the search point and rejects 23,803 places before it finds 20 matches. If the nearest matches were in another city, the scan would read most of the table.

You can stop the scan at 5 km with one more condition in the WHERE clause:

AND ST_DWithin(geog, ST_Point(-73.9855, 40.7580, 4326)::geography, 5000)

That change makes “pho” faster, at 13 ms, but makes “coffee” slower, at 80 ms. With a radius, Postgres chose the BitmapAnd plan in this run. For “coffee”, that plan collects about 39,000 matches and sorts all of them to return 20 rows.

Querycoffeepho
Nearest 20, no radius0.2 ms36 ms
Nearest 20 within 5 km80 ms13 ms

Neither query is fast for both words.

Why the Planner Can’t Pick the Right Plan

The planner chooses a plan from row estimates, and it assumes that words and locations are independent. It has no way to know that pho places cluster in Seattle. ANALYZE collects statistics for each column separately, and CREATE STATISTICS, which tracks relationships between columns, doesn’t support spatial or full-text conditions.

Speed Up Geo and Text Queries with a Multicolumn GiST Index

GiST indexes support tsvector columns, and a GiST index can have more than one column. A multicolumn GiST index can check the location condition and the text condition in the same scan:

CREATE INDEX places_geog_tsv_gist ON places USING gist (geog, search_tsv);

Run the “pho” query again. The text condition moves from Filter to Index Cond:

Limit
  ->  Index Scan using places_geog_tsv_gist on places
        Index Cond: (search_tsv @@ '''pho'''::tsquery)
        Order By: (geog <-> '...'::geography)

Postgres no longer fetches 23,803 rows and rejects them one at a time. The index skips each branch that cannot contain “pho”.

With the multicolumn index, all four queries take 0.10–0.14 ms.

The multicolumn index has costs. Measure them on your own data before you add the index in production:

  1. The index is large. The multicolumn index is 264 MB. The location index is 142 MB, and the text index is 19 MB.
  2. Writes are slower. An insert of 200,000 rows takes 4.0 s with the multicolumn index and 2.0 s without it.
  3. Long text reduces the benefit. GiST stores a compressed signature of each tsvector. A long document fills its signature, and then the index cannot skip it. Index short fields, such as names and short descriptions.

Rank Results by Relevance and Distance

Distance alone is often the wrong sort order. For the search “ramen open late”, a ramen place 150 m away that is open late should rank above a cafe 10 m away that only says it is open daily.

An ORDER BY on a formula such as ts_rank(...) / distance cannot use an index. Use the index to get the 200 nearest matches, and then score only those rows.

The query uses to_tsquery with | (OR), so a place that matches only some of the words is still a candidate. websearch_to_tsquery would require every word to match:

WITH q AS (
	SELECT to_tsquery('english', 'ramen | open | late') AS query
),
candidates AS (
	SELECT
		p.id,
		p.name,
		p.search_tsv,
		p.geog <-> ST_Point(-73.9855, 40.7580, 4326)::geography AS meters
	FROM places p, q
	WHERE p.search_tsv @@ q.query
	ORDER BY meters
	LIMIT 200
)
SELECT
	c.name,
	round(c.meters) AS meters,
	ts_rank(c.search_tsv, q.query) / (1 + c.meters / 1000) AS score
FROM candidates c, q
ORDER BY score DESC
LIMIT 20;

Here is part of the result, with the scores rounded. A ramen place 121 m away ranks first, above closer places that match fewer of the words:

         name          | meters | score
-----------------------+--------+-------
 Urban Ramen Co.       |    121 | 0.343
 ...
 Little Ramen Co.      |     57 | 0.287
 ...
 Harbor Coffee Kitchen |     44 | 0.233
 ...
 Corner Ramen House    |     14 | 0.220

The nearest match, “Corner Coffee Co.” at 10 m, only says it is open daily. It is not in the top 20.

The query runs in about 0.5 ms. The candidate step has no radius on purpose: “open” is a common word, so the nearest-first scan finds 200 matches quickly. With a 5 km radius, the same query takes about 200 ms. The scoring formula is an example. Tune the distance decay and the candidate limit for your data.

Limits of Geo Search in Postgres

The multicolumn index makes the queries fast. Four problems remain:

  1. Typos return nothing. A search for “phoo” returns zero rows. Fuzzy matching needs the pg_trgm extension and an index to keep it fast.
  2. Prefix search needs a different function. websearch_to_tsquery does not match prefixes. Search-as-you-type needs to_tsquery with the :* syntax.
  3. You write the ranking. ts_rank has no distance input. Every ranking formula is SQL that you write and maintain.
  4. The best index depends on your data. The multicolumn index helps when words cluster by location. That distribution changes as your data grows.

Alternative Approaches: Purpose-Built Search Engines

Search engines such as Typesense treat location as a field type. Typesense runs the text condition, the geo filter, and the geo sort in one search request, so you do not choose between indexes or depend on a query planner.

Geo Search in Typesense

The examples assume a running Typesense server and a configured client. See the Typesense installation guide.

Add a geopoint field to the collection schema. description is optional because the Postgres column can be NULL:

client.collections().create({
	name: 'places',
	fields: [
		{ name: 'name', type: 'string' },
		{ name: 'description', type: 'string', optional: true },
		{ name: 'category', type: 'string', facet: true },
		{ name: 'location', type: 'geopoint' }
	]
})

Export the rows as JSON lines. Typesense needs a string id, and a geopoint is a [latitude, longitude] array:

docker exec postgis-lab psql -U postgres -At -v FETCH_COUNT=10000 -c "
SELECT json_build_object(
	'id', id::text,
	'name', name,
	'description', description,
	'category', category,
	'location', json_build_array(ST_Y(geog::geometry), ST_X(geog::geometry))
)
FROM places" > places.jsonl

Import the file. Typesense returns HTTP 200 even when some documents fail, so the command prints the number of failed documents, which must be 0:

curl -s -X POST 'http://localhost:8108/collections/places/documents/import?action=create&batch_size=10000' \
	-H "X-TYPESENSE-API-KEY: ${TYPESENSE_API_KEY}" \
	--data-binary @places.jsonl | grep -c '"success":false'

Note

PostGIS stores points longitude first, but a Typesense geopoint is latitude first. That is why the export puts ST_Y (latitude) before ST_X (longitude).

The “pho near Times Square” query is one search request with a radius filter and a distance sort:

client.collections('places').documents().search({
	q: 'pho',
	query_by: 'name,description',
	per_page: 20,
	filter_by: 'location:(40.7580, -73.9855, 5 km)',
	sort_by: 'location(40.7580, -73.9855):asc'
})

Each hit includes geo_distance_meters, so your app does not calculate the distance again.

Typesense times are the median server-reported search_time_ms:

Nearest 20Postgres, two indexesPostgres, multicolumn indexTypesense
“coffee”0.2 ms0.12 ms100 ms
“pho”36 ms0.10 ms4 ms
“coffee” within 5 km80 ms0.13 ms69 ms
“pho” within 5 km13 ms0.14 ms53 ms
“phoo” within 5 kmNo resultsNo results53 ms, finds pho
“ramen open late”, ranked, 5 km198 ms332 ms81 ms

The multicolumn index is fastest for nearest-first queries, but it makes the ranked query slower and doesn’t handle typos. Typesense time grows with the number of text and filter matches, not with the plan: ~420,000 places match “coffee”, and ~187,000 are within 5 km.

What Typesense Handles for You

  1. One sort_by value combines relevance and distance. The strategy differs from the SQL query, which scores the 200 nearest matches with a continuous distance penalty. Typesense puts results within 5 km into 1 km buckets (precision), orders each bucket by text match and then by distance. text_match_type: 'sum_score' adds the name and description scores, so a word in the name counts. On the sample data, the top 6 results were the same six documents as the SQL query’s:
client.collections('places').documents().search({
	q: 'ramen open late',
	query_by: 'name,description',
	per_page: 20,
	text_match_type: 'sum_score',
	filter_by: 'location:(40.7580, -73.9855, 5 km)',
	sort_by: 'location(40.7580, -73.9855, precision: 1 km):asc,_text_match:desc,location(40.7580, -73.9855):asc'
})
  1. Typo tolerance and prefix search are on by default. A search for “ram” finds ramen places. By default, Typesense allows 1 typo in words of 4 or more characters, and 2 typos in words of 7 or more characters. The min_len_1typo and min_len_2typo parameters change these limits.

Typesense also has costs. It does not read your Postgres tables, so you keep the search index up to date with a sync job or with change data capture. It keeps the index in memory: with the 2 million sample places, the Typesense process used ~350 MiB of active memory (typesense_memory_active_bytes).

Conclusion

Postgres can serve fast location search with ST_DWithin for radius filters, <-> for nearest-neighbor search, and a multicolumn GiST index for rare words. The cost is a larger index, slower writes, and ranking logic in SQL. Typo tolerance needs the pg_trgm extension, and semantic search needs the pgvector extension and embeddings that you generate yourself. Both usually need an extra index to stay fast.

Typesense adds typo tolerance, prefix search, and distance-aware ranking in one request. It also supports semantic and hybrid search with built-in embedding models. The cost is memory and a sync job. If your users type complete, correctly spelled words, stay with Postgres. If they need search-as-you-type, typo tolerance, or semantic search, a search engine is worth it.