Open ndrean opened 1 year ago
Relevant real-world project where we used this: https://github.com/dwyl/phoenix-uk-postcode-finder-example π
I understand you have a DIY method and calculate the distance yourself and check against the whole ETS/DB. You could have saved on computations in your calc_distance
by doing a flat world approximation since you are working locally instead of doing spherique computations. I did use Postgres functions. It is programmed in C so way faster than the old Erlang. I observed that the query becomes quickly more efficient as you submit more queries, and very quickly the response time is almost independent of the number of new entries (talking < 20ms for 500 entries). This means it builds up a spatial GIST index very efficiently but I understood this is costly in terms of disk space.
Good feedback. Thanks! π
Guide on how to use
Postgis
withPhoenix
Once you created the Postgis extension,
you may want to use the package
geo_postgis
to use the types Postgis provides as fields in migration and schemaAdd it to your mix:
Configure it. In the "config.exs", if you use
Jason
, declare:and declare the Postgis types:
so create a module
my_app/postgres_types.ex
:Now you are ready to use fields such as
Geo.PostGIS.Geometry
in your schemas. For example, I want to create the type "LINESTRING" with GEOGRAPHY and the 4326 projection (the one used by the GPS), so in a migration:NB: if you are looking for distances between geometries in your dataset, for example a nearest neighbour search, you may want to use a special spatial index GIST. This will accelerate the spatial queries (at the cost of space in your db) and allow the usage of the distance operator <->. Tested on finding among 1000 geometries the nearest geometries within a given distance to a point. The results for the first search give a response of < 100ms, and then < 10ms for consecutive searches.
and in your schema, you can use it:
You are also likely to use GeoJSON format (but not restricted to). You can render this format with Postgis. An example of query using the distance
<->
operator, theST_Distance
function, theST_MakePoint
function and rendering inGeoJSON
format. You will be able to send this data directly to a Javascript library (LeafletJS
ormaplibre
) and render the GeoJSON format easily.If you don't want GeoJSON formatted results but rather use your schema, prepare this query:
And run this query with Ecto and load the results using your schema: (note that the Postgres placeholders
$i
are interpolated with a list, the second argument ofRepo.query
function).