rnjai
rnjai

Reputation: 1135

Solr - Order results by proximity to number

I am using solr to get results based on the search text entered by the user.
I want to order the results based on proximity to the calories field of the document as shown below.
I have used Range (calories:[0 TO 300]) however that doesnt fulfill my needs.

{
  "food_group":"Proteins",
  "carbs":"6.295",
  "protein":"13.729",
  "fat":"2.551",
  "calories":103.0
}

For example if user enters 100 as calories i want to show the document with 101 before the document with 97 and so on...(There is no sorting logic in this)

Upvotes: 0

Views: 174

Answers (1)

Ashraful Islam
Ashraful Islam

Reputation: 12830

You can use abs(sub(user_calories, calories)) function as sort

Example for user input 100 :

q = "calories:[0 TO 300]",
sort = "abs(sub(100,calories)) asc"

Example Url :

http://127.0.0.1:8983/solr/test/select?q=calories%3A%5B0+TO+300%5D&sort=abs(sub(100%2Ccalories))+asc

Upvotes: 1

Related Questions