DEV Community

adithyasrinivasan
adithyasrinivasan

Posted on • Originally published at adithya.dev on

Elasticsearch - No mapping found for [field_name] in order to sort on

I use Laravel Scout (sometimes PHP) with Elasticsearch making use of this great package Scout Elasticsearch driver. This allows for the possibility of sorting / ordering records directly from Elasticsearch.

Once you create your index, write a query to sort your records by a field to get the latest posts, you might be hit with the following error

Elasticsearch\Common\Exceptions\BadRequest400Exception: 

{
    "error": {
        "root_cause": [
            {
                "type": "query_shard_exception",
                "reason": "No mapping found for [field_name] in order to sort on",
                "index_uuid": "Rk1oQl22TH6vKzgTJCn57w",
                "index": "index-name"
            }
        ],
        "type": "search_phase_execution_exception",
        "reason": "all shards failed",
        "phase": "query",
        "grouped": true,
        "failed_shards": [
            {
                "shard": 0,
                "index": "index-name",
                "node": "Nd1diFCdQVO9T-gx1dfazg",
                "reason": {
                    "type": "query_shard_exception",
                    "reason": "No mapping found for [field_name] in order to sort on",
                    "index_uuid": "Rk1oQl22TH6vKzgTJCn57w",
                    "index": "index-name"
                }
            }
        ]
    },
    "status": 400
}

 in file /var/www/html/vendor/elasticsearch/elasticsearch/src/Elasticsearch/Connections/Connection.php on line 675

Enter fullscreen mode Exit fullscreen mode

No reason to panic, your query statement, connection with Elasticsearch is all good. The reason this error pops up is because you have no data in your mapping, therefore Elasticsearch cannot sort it. If you're coming from MySQL, this is a weird quirk to get used to.

From Elasticsearch documentation:

Ignoring Unmapped Fieldsedit

By default, the search request will fail if there is no mapping associated with a field. The unmapped_type option allows you to ignore fields that have no mapping and not sort by them. The value of this parameter is used to determine what sort values to emit.

If any of the indices that are queried doesn’t have a mapping for price then Elasticsearch will handle it as if there was a mapping of type long, with all documents in this index having no value for this field. Here is an example of how it can be used.

GET /_search
{
  "sort" : [
    { "field_name" : {"unmapped_type" : "long"} }
  ],
  "query" : {
    "term" : { "product" : "chocolate" }
  }
}
Enter fullscreen mode Exit fullscreen mode

With PHP / Laravel, you can either append unmapped_type or fill up your data before the initial search. Either of the approaches should solve it.

Top comments (0)