# Sort that involves nested values and non nested values (without iterating nested array)

**URL:** <https://discuss.elastic.co/t/sort-that-involves-nested-values-and-non-nested-values-without-iterating-nested-array/30086>\
**Category:** Elasticsearch\
**Created:** [September 27, 2015, 3:18pm UTC](https://discuss.elastic.co/t/sort-that-involves-nested-values-and-non-nested-values-without-iterating-nested-array/30086 "2015-09-27T15:18:50Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![cldsnchz](https://avatars.discourse-cdn.com/v4/letter/c/278dde/32.png) [@cldsnchz](https://discuss.elastic.co/u/cldsnchz)\
**Post date:** [September 27, 2015, 3:18pm UTC](https://discuss.elastic.co/t/sort-that-involves-nested-values-and-non-nested-values-without-iterating-nested-array/30086/1 "2015-09-27T15:18:50Z")

</div>

Hi, I want to execute a sort logic that involves nested and non nested values. But I don't know how to get a particular nested value without iterating the nested array.

Having this mapping:

```
{
  "mapping":{
    "item":{
      "properties":{
        "title":{ "type":"string" },
        "type":{ "type":"string", "index":"not_analyzed" }
        "createTime":{ "type":"date" },
        "tracks":{
          "type":"nested",
          "properties":{
            "userId":{ "type":"string", "index":"not_analyzed" }
            "viewTime":{ "type":"date" },
          }
        }
      }
    }
  }
}

```

And I want to execute a sort with this logic

```
// params userId and currentTime
if (doc['type'].value == 'X') {
    return doc['createTime'].value
}
else {
    // This is the problematic condition
    if (exists doc['tracks.viewTime'].value for userId) {
        return doc['tracks.viewTime'].value for userId
    }
    else {
        return currentTime;
    }
}

```

Is there any way to do this without iterating all tracks? maybe combining different sorts (script, nested, etc)  
And if there is a way to do it with nested values, is there a way to do something similar with parent/child mappings (where each track is a child)?

Thanks, Claudio.

---

<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:** [July 5, 2017, 11:47pm UTC](https://discuss.elastic.co/t/sort-that-involves-nested-values-and-non-nested-values-without-iterating-nested-array/30086/2 "2017-07-05T23:47:53Z")

</div>

Closed on July 5, 2017, 11:47pm UTC


