Search code examples
redisredisearch

RediSearch sort by numeric field then by distance when using geofilter


How can I sort results, first by some numeric field (for example by price) then by distance when using GEOFILTER in RediSearch?


Solution

  • The FT.SEARCH command does not support multiple fields with SORTBY.

    However you can use the FT.AGGREGATE command and the geodistance function for this.

    Here is an example using REDIS-CLI:

    HSET doc1 price 9.99 location "-122.41,37.77"
    (integer) 0
    HSET doc2 price 19.99 location "-122.40,37.78"
    (integer) 0
    HSET doc3 price 19.99 location "-122.42,37.79"
    (integer) 0
    FT.CREATE idx SCHEMA price NUMERIC SORTABLE location GEO SORTABLE
    OK
    FT.AGGREGATE idx "@price:[0 100]" APPLY 'geodistance(@location, "-122.39,37.78")' AS dist SORTBY 4 @price DESC @dist ASC
    1) (integer) 3
    2) 1) "location"
       2) "-122.40,37.78"
       3) "dist"
       4) "879.1"
       5) "price"
       6) "19.99"
    3) 1) "location"
       2) "-122.42,37.79"
       3) "dist"
       4) "2862.08"
       5) "price"
       6) "19.99"
    4) 1) "location"
       2) "-122.41,37.77"
       3) "dist"
       4) "2080.58"
       5) "price"
       6) "9.99"