# Understanding what value will be used for sorting by nested field if field has a several nested values

**URL:** <https://discuss.elastic.co/t/understanding-what-value-will-be-used-for-sorting-by-nested-field-if-field-has-a-several-nested-values/320956>\
**Category:** Elasticsearch\
**Created:** [December 10, 2022, 10:51pm UTC](https://discuss.elastic.co/t/understanding-what-value-will-be-used-for-sorting-by-nested-field-if-field-has-a-several-nested-values/320956 "2022-12-10T22:51:17Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Yuri\_Khmelevsky](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/yuri_khmelevsky/32/114520_2.png) [@Yuri\_Khmelevsky](https://discuss.elastic.co/u/Yuri_Khmelevsky)\
**Post date:** [December 10, 2022, 10:51pm UTC](https://discuss.elastic.co/t/understanding-what-value-will-be-used-for-sorting-by-nested-field-if-field-has-a-several-nested-values/320956/1 "2022-12-10T22:51:17Z")

</div>

I have the following mapping

```auto
{
  "mappings": {
    "properties": {
      "rank-by-views": {
        "type": "nested",
        "properties": {
          "id": {"type": "keyword"},
          "value": {"type": "keyword"}
        }
      }
    }
  }
}

```

And I need to sort bases on rank of specified view or if view rank is not exist for this view use default rank:

```auto
{
  "sort": [
    {
      "rank-by-views.value": {
        "order": "desc",
        "nested": {
          "path": "rank-by-views",
          "filter": {
            "bool": {
              "should": [
                {
                  "term": {
                    "rank-by-views.id": "view-1"
                  }
                },
                {
                  "term": {
                    "rank-by-views.id": "default"
                  }
                }
              ]
            }
          }
        }
      }
    }
  ]
}

```

I have cases when I have default and view rank but in this case I need to use view rank and ignore default. Based on tests looks like it works right now but I don't understand how ES decided what value in nested field need to use for sorting if filter return a few values

---

<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:** [January 7, 2023, 10:51pm UTC](https://discuss.elastic.co/t/understanding-what-value-will-be-used-for-sorting-by-nested-field-if-field-has-a-several-nested-values/320956/2 "2023-01-07T22:51:23Z")

</div>

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