# Conditional sort

**URL:** <https://discuss.elastic.co/t/conditional-sort/197372>\
**Category:** Elasticsearch\
**Created:** [August 29, 2019, 3:06pm UTC](https://discuss.elastic.co/t/conditional-sort/197372 "2019-08-29T15:06:10Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Kennedy\_Batista](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/kennedy_batista/32/53304_2.png) [@Kennedy\_Batista](https://discuss.elastic.co/u/Kennedy_Batista)\
**Post date:** [August 29, 2019, 3:06pm UTC](https://discuss.elastic.co/t/conditional-sort/197372/1 "2019-08-29T15:06:10Z")

</div>

Hi, I have the following index:

```
                "norm_id": {
                    "type": "keyword"
                },
                "precedence": {
                    "type": "float"
                },
                "root_norm_id": {
                    "type": "keyword"
                },
                "status_id": {
                    "type": "integer"
                },
                "title": {
                    "type": "text"
                },
                "type_id": {
                    "type": "integer"
                }

```

And I need to get all documents that have `root_norm_id` = some ID and then sort by `norm_id` and `precedence` respectively. Also, I need that all documents with `type_id = 3` to be at the bottom, but I don't know how to do that. Can someone help me?

Thanks.

---

<div class="post-metadata">

**Author:** ![iti](https://avatars.discourse-cdn.com/v4/letter/i/b19c9b/32.png) [@iti](https://discuss.elastic.co/u/iti)\
**Post date:** [August 29, 2019, 5:15pm UTC](https://discuss.elastic.co/t/conditional-sort/197372/2 "2019-08-29T17:15:32Z")

</div>

Try this:

```
   {
  "query": {
    "function_score": {
      "query": {
        "match": {
          "root_norm_id": 1234
        }
      },
      "boost": "5",
      "functions": [
        {
          "filter": {
            "match_all": {}
          },
          "weight": 1
        },
        {
          "filter": {
            "match": {
              "type_id ": 3
            }
          },
          "weight": 2
        }
      ]
    }
  },
  "sort": [
    {
      "_score": {
        "order": "asc"
      },
      "norm_id ": {
        "order": "asc"
      },
      "precedence ": {
        "order": "asc"
      }
    }
  ]
}
```

---

<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:** [September 26, 2019, 5:15pm UTC](https://discuss.elastic.co/t/conditional-sort/197372/3 "2019-09-26T17:15:46Z")

</div>

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