I have a collection of first names.
team dhoni
dhoni1
dibeesh 200
bb vineesh
devan
I want to sort it alphabetically ascending order (A - Z) like the following order
bb vineesh
devan
dhoni1
dibeesh 200
team dhoni
Mapping
"first_name": {
"type": "string",
"store": "true"
},
I have tried
{
"sort": [
{
"first_name": {
"order": "asc"
}
}
],
"query": {
"match_all": {
}
}
}
When i run this query am getting the names in following order.
dibeesh 200
bb vineesh
devan
team dhoni
dhoni1
Elastic search taking first names with number as first preference.
How can I prevent this?
You can sort Elasticsearch results using the sort keyword. The sort query requires you to provide a field under which to sort. Elasticsearch does not support sorting on fields of type text.
In Elasticsearch, the relevance score is represented by the floating-point number returned in the search results as the _score, so the default sort order is _score descending.
The sort is defined on a per field level, with special field name for _score to sort by score, and _doc to sort by index order. _doc has no real use-case besides being the most efficient sort order. So if you don't care about the order in which documents are returned, then you should sort by _doc .
The _score in Elasticsearch is a way of determining how relevant a match is to the query. The default scoring function used by Elasticsearch is actually the default built in to Lucene which is what Elasticsearch runs under the hood.
I had a similar issue and the other answer didn't quite get it for me. I referred to this documentation instead, and was able to solve by mapping like this
"name": {
"type": "string",
"analyzer": "english",
"fields": {
"raw": {
"type": "string",
"index": "not_analyzed"
}
}
}
and then querying and sorting like this
{
"query": {
"match": {
"name": "dhoni"
}
},
"sort": {
"name.raw": {
"order": "asc"
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With