# Sum by quantity and sort by lowest price

**URL:** <https://discuss.elastic.co/t/sum-by-quantity-and-sort-by-lowest-price/311242>\
**Category:** Elasticsearch\
**Created:** [August 2, 2022, 7:57pm UTC](https://discuss.elastic.co/t/sum-by-quantity-and-sort-by-lowest-price/311242 "2022-08-02T19:57:23Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![79g](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/79g/32/109191_2.png) [@79g](https://discuss.elastic.co/u/79g)\
**Post date:** [August 4, 2022, 8:16am UTC](https://discuss.elastic.co/t/sum-by-quantity-and-sort-by-lowest-price/311242/2 "2022-08-04T08:16:49Z")

</div>

Hello @brampurnot,

try these searches:

For the first query:

```auto
GET discuss/_search
{
  "query": {
    "range": {
      "quantity": {
        "lte": 200
      }
    }
  },
  "sort": [
    {
      "price": "asc"
    },
    "_score"
  ]
}

```

Second query:

```auto
GET discuss/_search
{
  "query": {
    "range": {
      "quantity": {
        "lte": 200
      }
    }
  },
  "sort": [
    {
      "price": "asc"
    },
    "_score"
  ],
  "aggs": {
    "lead_time_avg": {
      "avg": {
        "field": "lead_time"
      }
    },
    "total_price": {
      "sum": {
        "script": {
          "lang": "painless",
          "inline": "doc['price'].value * doc['quantity'].value"
        }
      }
    }
  }
}

```

Used data:

```auto
PUT /discuss
PUT /discuss/_mapping
{
  "properties": {
    "description": {
      "type": "text"
    },
    "quantity": {
      "type": "double"
    },
    "price": {
      "type": "double"
    },
    "lead_time": {
      "type": "double"
    }
  }
}

POST discuss/_doc/
{
  "description": "Product 1",
  "quantity": "200",
  "price": "4",
  "lead_time": "2"
}
POST discuss/_doc/
{
  "description": "Product 2",
  "quantity": "150",
  "price": "3",
  "lead_time": "5"
}
POST discuss/_doc/
{
  "description": "Product 3",
  "quantity": "275",
  "price": "5",
  "lead_time": "14"
}

GET discuss/_search
{
  "query": {
    "range": {
      "quantity": {
        "lte": 200
      }
    }
  },
  "sort": [
    {
      "price": "asc"
    },
    "_score"
  ]
}

```

I attach you also the output:

 ![query](https://us1.discourse-cdn.com/elastic/original/3X/0/9/09f5aeae575ae7e615513a20f9824ed10af7bfc7.png)

Hope it helps 🙂

---

_[View the full topic](https://discuss.elastic.co/t/sum-by-quantity-and-sort-by-lowest-price/311242)._
