Search code examples
sqlpostgresqlpostgishstore

PostGis search query on hstore tags


I am writing a search client, to query postgis db.

The search query will be,

    SELECT tags->'name' AS name,ST_Transform(way,4326) AS pt_lonlattext 
FROM planet_osm_point WHERE lower(tags->'name') LIKE '%school%'

Now, I need the results in such a way that,

fully matched results should be given priority than partially matched ones. e.g. The results that has only 'school' in name should be first in the returned list, followed by results which has 'primary school','high school' etc..

Is there a way to re-construct the above query to get the desired results?


Solution

  • something like this?

    select
        tags->'name' as name,
        ST_Transform(way,4326) as pt_lonlattext 
    from planet_osm_point
    where lower(tags->'name') LIKE '%school%'
    order by case when lower(tags->'name') = 'school' then 0 else 1 end
    

    or, more DRY version:

    with cte as (
        select
            tags->'name' as name,
            ST_Transform(way,4326) as pt_lonlattext 
        from planet_osm_point
    )
    select name, pt_lonlattext 
    from cte
    where lower(name) like '%school%'
    order by case when lower(name) = 'school' then 0 else 1 end