# Sorting script with tiebreaker

**URL:** https://discuss.elastic.co/t/sorting-script-with-tiebreaker/348528
**Category:** Elasticsearch
**Created:** [December 4, 2023, 8:14am UTC](https://discuss.elastic.co/t/sorting-script-with-tiebreaker/348528 "2023-12-04T08:14:38Z")
**Posts on this page:** 3
**Page:** 1

<div class="post-metadata">

### Author: ![\_baba](https://avatars.discourse-cdn.com/v4/letter/_/ecb155/32.png) [@\_baba](https://discuss.elastic.co/u/_baba)
#### Post date: [December 4, 2023, 8:14am UTC](https://discuss.elastic.co/t/sorting-script-with-tiebreaker/348528/1 "2023-12-04T08:14:38Z")

</div>

Hi,

We have multiple documents in an index with duplicate field value (product\_id). I want to sort based on product\_id with a condition that for 2 records having same product\_id, sort based on product\_cost.

Recreation steps:

```auto
PUT /product
{
    "mappings" : {
        "properties" : {
			"product_id": { "type" : "long" },
			"product_cost": { "type" : "long" }
        }}}
        

POST product/_doc
{
			"product_id": 22,
			"product_cost": 1232
}

POST product/_doc
{
			"product_id": 36,
			"product_cost": 2314
}

POST product/_doc
{
			"product_id": 36,
			"product_cost": 8892
}

POST product/_doc
{
			"product_id": 87,
			"product_cost": 1287
}

POST product/_doc
{
			"product_id": 100,
			"product_cost": 6372
}

POST product/_doc
{
			"product_cost": 3452
}

```

Please note that there are dirty records with no product\_name filed and for those cases I want to assign default value of -9999 and sort accordingly.

Can you please help me with a sort script. Challenge that I'm facing is with the tie breaker in the script.

---

<div class="post-metadata">

### Author: ![\_baba](https://avatars.discourse-cdn.com/v4/letter/_/ecb155/32.png) [@\_baba](https://discuss.elastic.co/u/_baba)
#### Post date: [December 4, 2023, 3:08pm UTC](https://discuss.elastic.co/t/sorting-script-with-tiebreaker/348528/2 "2023-12-04T15:08:25Z")

</div>

Hi, can someone help here.

---

<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 1, 2024, 3:09pm UTC](https://discuss.elastic.co/t/sorting-script-with-tiebreaker/348528/3 "2024-01-01T15:09:25Z")

</div>

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