AI Features

Geolocating the Nearest Pub

Learn about kNN search and indexing in kNN search.

kNN search

To implement a kNN search in PostgreSQL, we need to order the result set with a distance operator, written <->. Here’s the full SQL for searching the pubs near a known position:

select id, name, pos
from pubnames
order by pos <-> point(-0.12,51.516)
limit 3;

With this geolocation, we obtain the following nearby pubs:

    id     │          name          │           pos           
═══════════╪════════════════════════╪════════════════
...
Ask