Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elastic search alphabetical sorting based on first character

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?

like image 524
Dibish Avatar asked Aug 08 '14 03:08

Dibish


People also ask

How do I sort names in Elasticsearch?

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.

What is the default sort order in Elasticsearch?

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.

How sort works in Elasticsearch?

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 .

What is _score in Elasticsearch?

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.


1 Answers

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"
        }
    }
}
like image 84
Tyler Avatar answered Nov 10 '22 02:11

Tyler