Skip to content

Instantly share code, notes, and snippets.

@kishorenc
Last active June 29, 2021 11:27
Show Gist options
  • Save kishorenc/1f537c728f89960048272a03d36bad01 to your computer and use it in GitHub Desktop.
Save kishorenc/1f537c728f89960048272a03d36bad01 to your computer and use it in GitHub Desktop.
Typesense geo preview

Usage:

Create a collection with a geopoint field:

curl -k "http://localhost:8108/collections" -X POST -H "Content-Type: application/json" \
      -H "X-TYPESENSE-API-KEY: ${TYPESENSE_API_KEY}" -d '{
        "name": "places", "num_memory_shards": 4,
        "fields": [
          {"name": "title", "type": "string" },
          {"name": "points", "type": "int32" }, 
          {"name": "location", "type": "geopoint"}
        ],
        "default_sorting_field": "points"
      }'

Add a record:

curl "http://localhost:8108/collections/places/documents" -X POST \
        -H "Content-Type: application/json" \
        -H "X-TYPESENSE-API-KEY: ${TYPESENSE_API_KEY}" \
        -d '{"points":1,"title":"Louvre Museuem", "location": [48.86093481609114, 2.33698396872901]}'

You can then query for records nearest to a given query latlong via a filter query:

filter_by=loc:(48.90615915923891, 2.3435897727061175, 5 km)

Full query:

http://localhost:8108/collections/places/documents/search?q=*&query_by=title&filter_by=location:(48.853,2.344,5 km)&x-typesense-api-key=abcd

The above example uses "5 km" as the radius, but you can also use miles, e.g. via 2 mi.

Once you filter the results within a radius, you can also sort the results in terms of proximity from a given location:

sort_by=location(48.853, 2.344):ASC,points:DESC

Here, we are sorting the records whose location field value is nearest to the point (48.853, 2.344).

And oh, you can also filter records within any arbitrary shaped polygon too! The polygon's points must be defined in a counter-clock-wise direction:

location:(48.8662, 2.3255, 48.8581, 2.3209, 48.8561, 2.3448, 48.8641, 2.3469)

Full query:

http://localhost:8108/collections/places/documents/search?q=*&query_by=title&filter_by=location:(48.8662, 2.3255, 48.8581, 2.3209, 48.8561, 2.3448, 48.8641, 2.3469)&x-typesense-api-key=abcd&sort_by=location(48.853, 2.344):ASC,points:DESC
@wandermonk1
Copy link

wandermonk1 commented Jun 29, 2021

I am using Typesense cloud. Unable to create a field with geopoint type in dashboard.

@kishorenc
Copy link
Author

@wandermonk1 Geo feature is only available in a recent release candidate build. If you can email me (contact@typesense.org) with your cluster ID I can upgrade your cluster to the RC build.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment