# Conditional sorting by different text fields in Elastic Search Query

**URL:** <https://discuss.elastic.co/t/conditional-sorting-by-different-text-fields-in-elastic-search-query/315231>\
**Category:** Elasticsearch\
**Created:** [September 27, 2022, 5:58am UTC](https://discuss.elastic.co/t/conditional-sorting-by-different-text-fields-in-elastic-search-query/315231 "2022-09-27T05:58:11Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![christianholsen](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/christianholsen/32/111321_2.png) [@christianholsen](https://discuss.elastic.co/u/christianholsen)\
**Post date:** [September 27, 2022, 5:58am UTC](https://discuss.elastic.co/t/conditional-sorting-by-different-text-fields-in-elastic-search-query/315231/1 "2022-09-27T05:58:11Z")

</div>

I have a problem sorting some data in an Elastic Search index.

My data in ES are documents with a default name and possibly translation of the name can be found in a translations nested structure:

```auto
[
{
    "defaultName": "item1 default name",
    "translations": [
        {
            "languageCode": "en",
            "name": "Item1 in english"
        },
        {
            "languageCode": "da",
            "name": "Item1 in danish"
        }
    ]
},
{
    "defaultName": "item2 default name",
    "translations": [
        {
            "languageCode": "en",
            "name": "Item2 in english"
        }
    ]
},
{
    "defaultName": "item3 default name",
    "translations": [] 
}
]

```

When I perform a blank search I need to sort the search result by default name or translated name depending on whether or not the name has been translated or not.

When I search in **english (en)** the sorting should be done between:

- Item1 in english
- Item2 in english
- Item3 default name

When I search in **danish (da)** the sorting should be done between:

- Item1 in danish
- Item2 default name
- Item3 default name

I have tried much to get there, but I would like hear if this is possible at all? and maybe a way to do it. I believe I cannot calculate custom scores in this scenario as the sorting is based on text comparison.

If everything fails my fallback solution is to populate non-existing translations with the default translation, but I don't like this solution as it seems much more clean to avoid duplicate data.

Can anyone help me out? 🙂

---

<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:** [October 25, 2022, 5:59am UTC](https://discuss.elastic.co/t/conditional-sorting-by-different-text-fields-in-elastic-search-query/315231/2 "2022-10-25T05:59:02Z")

</div>

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