# Filter and sort based on attributes in Terms lookup document

**URL:** <https://discuss.elastic.co/t/filter-and-sort-based-on-attributes-in-terms-lookup-document/200241>\
**Category:** Elasticsearch\
**Created:** [September 19, 2019, 2:51pm UTC](https://discuss.elastic.co/t/filter-and-sort-based-on-attributes-in-terms-lookup-document/200241 "2019-09-19T14:51:57Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![come\_along\_bort](https://avatars.discourse-cdn.com/v4/letter/c/67e7ee/32.png) [@come\_along\_bort](https://discuss.elastic.co/u/come_along_bort)\
**Post date:** [September 27, 2019, 1:36pm UTC](https://discuss.elastic.co/t/filter-and-sort-based-on-attributes-in-terms-lookup-document/200241/2 "2019-09-27T13:36:51Z")

</div>

Have still not found a solution but I found [this thread](https://discuss.elastic.co/t/terms-lookup-sort/83084/2) that discusses the sorting, but I am unable to get it to work.

Following the directions from there here's some more detail on what I'm trying to do.

1. I put a nested mapping for the collection type:

```auto
PUT /index/collection/_mappings
{
     "properties": {
         "items": {
             "type": "nested" 
         }
     }
}

```

1. I index some documents/things:

```auto
POST /index/thing/_bulk
    { "index":{ "_id": 1 } }
    { "title":"One thing"}
    { "index":{ "_id": 2 } }
    { "title":"Second thing"}
    { "index":{ "_id": 3 } }
    { "title":"Three things"}
    { "index":{ "_id": 4 } }
    { "title":"And so fourth"}
    { "index":{ "_id": 5 } }
    { "title":"Five things"}

```

1. I index the collection, which has three items in the following order:

```auto
PUT /index/collection/1
{
    "items": [
        {"id": 1, "time_added": "2017-08-07T09:07:15.000Z", "condition": "fair"},
        {"id": 3, "time_added": "2019-08-07T09:07:15.000Z", "condition": "good"},
        {"id": 4, "time_added": "2016-08-07T09:07:15.000Z", "condition": "poor"}
    ]
}

```

1. I run a search with a terms lookup, filtering the `documents` that are in the `collection`

```auto
GET "index/thing/_search"
{
    "query" : {
        "terms" : {
            "_id" : {
                "index" : "index",
                "type" : "collection",
                "id" : 1,
                "path" : "items.id"
            }
        }
    },        
    "sort": [
        { "items.id" : {"order" : "desc"}}
    ]
}

```

The order I expect is `1,3,4` (which is the order in the collection) but i get them in `4,1,3` (and in fact changing the order from `desc` to `asc` does not change the order). Am I missing something?

c.c. @polyfractal as you had an answer on the linked thread (I hope tagging like this is acceptable, quite a n00b to this forum).

---

_[View the full topic](https://discuss.elastic.co/t/filter-and-sort-based-on-attributes-in-terms-lookup-document/200241)._
