# Sorting on keyword not working as expected

**URL:** <https://discuss.elastic.co/t/sorting-on-keyword-not-working-as-expected/253959>\
**Category:** Elasticsearch\
**Created:** [November 1, 2020, 8:14pm UTC](https://discuss.elastic.co/t/sorting-on-keyword-not-working-as-expected/253959 "2020-11-01T20:14:48Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![F\_eq\_kx](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/f_eq_kx/32/62217_2.png) [@F\_eq\_kx](https://discuss.elastic.co/u/F_eq_kx)\
**Post date:** [November 1, 2020, 8:14pm UTC](https://discuss.elastic.co/t/sorting-on-keyword-not-working-as-expected/253959/1 "2020-11-01T20:14:48Z")

</div>

I am storing Windows UNC paths in a `path` field with the following mapping:

```auto
"path": {
    "type": "text",
    "fields": {
        "keyword": {
            "type": "keyword"
        },
        "tree": {
            "type": "text",
            "analyzer": "custom_path_tree"
        }
    }
}

```

When I run this query:

```auto
{
    "sort": [
        {
            "fs.path.keyword": {
                "order": "desc"
            }
        }
    ],
    "_source": "path",
    "size": 1
}

```

I get a document with a path like `\\foo\bar\FN1\FFF`. However, looking at the other documents in the index, I see others with a path `\\foo\bar\FN15\EEE`.

I would have thought `\` would come before `5` when sorting against a keyword field.

Why is it doing this and how can I get Elasticsearch to sort this field so that `\\foo\bar\FN15\EEE` comes after `\\foo\bar\FN1\FFF`?

---

<div class="post-metadata">

**Author:** ![Mark\_Harwood](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/mark_harwood/32/10538_2.png) [@Mark\_Harwood](https://discuss.elastic.co/u/Mark_Harwood)\
**Post date:** [November 2, 2020, 11:56am UTC](https://discuss.elastic.co/t/sorting-on-keyword-not-working-as-expected/253959/2 "2020-11-02T11:56:37Z")

</div>

You're using descending order and `\` comes before `5` in that order - e.g. like reading [this table](https://www.ascii-code.com/) backwards

> [@F\_eq\_kx](#):
>
> how can I get Elasticsearch to sort this field

A common technique when sorting numbers as string is to zero pad appropriately e.g. use `FN001` instead of `FN1`. I doubt that's a good answer for examining existing file names but if that's the sort logic you need then that's how you'll have to prep your content

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)\
**Post date:** [November 30, 2020, 11:56am UTC](https://discuss.elastic.co/t/sorting-on-keyword-not-working-as-expected/253959/3 "2020-11-30T11:56:38Z")

</div>

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.
