Reputation: 51
I have field called "rating" in data. The value of this field,would be one of the following "good","average" or "bad". What Im trying to get is to sort the documents according to the "rating" field values they posses. Since the field value is a string how can i do a sort based on that value?
Upvotes: 2
Views: 5476
Reputation: 2689
I tried with the Vineeth's answer and ran into "[_script] unknown field [params], parser not found"
I made this change and it worked for me:
"sort": {
"_script": {
"type": "number",
"script": {
"lang": "painless",
"source": "params.get(doc['rating'].value)",
"params": {
"good": 2,
"average": 1,
"bad": 0
}
},
"order": "asc"
}
}
Upvotes: 0
Reputation: 3019
You can sort on a text field (I recommend to do that on non-analyzed fields), the documents will be sorted in alphabetical order if sorted in ascending order and in reverse alphabetical order if sorted in descending order.
Example:
POST index/type/_search
{
"query":{
"match_all": {}
},
"sort":{"my_not_analyzed_field":{"order":"asc"} }
}
This code will match every document in index index of type type and will sort them in alphabetical order.
NB: It theoretically works on analyzed fields but the results will be surprising if the contents have been tokenized since the results will not be sorted on the basis of the start of the string but using any word (token) of the string, taking the more "advantageous" one.
Upvotes: 1
Reputation: 19253
As far as I understand,you want the values in the "rating" field to be given weights and then sort them in the descending order. You can use the following script for that:
"sort": {
"_script": {
"script": "factor.get(doc[\"rating\"].value)",
"type": "number",
"params": {
"factor": {
"good": 2,
"average": 1,
"bad": 0
}
},
"order": "desc"
}
}
This will give the elements in the "rating" array numerical values and then sort the documents in the descending order. More on this can be found in here
Upvotes: 5