0

I want to query to my Elastic-Search to get minimum price of values which have only positive value. My prices can also be zero and -1; so I don't want my min-aggregation to return 0 or -1. I know that I should add a script to the query (or filter), but I don't know how. My current code:

public function minPriceAggregation($minName, $field = 'price')
    {
        if ($field) {
            $this->aggregation[$minName] = [
                'min' => [
                    'field' => $field
                ]
            ];
        }
        return $this;
    }

This query always returns -1; I want to ignore the values < 0 and only have the minimum in my positive values.

Something like:

public function minPriceAggregation($minName, $field = 'price')
    {
        if ($field) {
            $this->aggregation[$minName] = [
                'min' => [
                    'field' => $field,
                    'script' => [
                        'source' => 'return _value > 0 ?: _value' //What's the correct script here??
                    ]
                ]
            ];
        }
        return $this;
    }

1 Answers1

1

Try this:

public function minPriceAggregation($minName, $field = 'price')
    {
        if ($field) {
            $this->aggregation[$minName] = [
                'min' => [
                    'script' => [
                        'source' => 'return Math.max(0, doc["price"].value)'
                    ]
                ]
            ];
        }
        return $this;
    }
Val
  • 207,596
  • 13
  • 358
  • 360
  • Math.max always returns 0 because my minimum value is -1. Suppose I have these values: [-1, 0, 5, 10, 15, ....]. I want my function to return 5; but your answer always returns 0 in my case. Is there any better option? – Matin Hajatdoost Feb 24 '20 at 09:04
  • `Math.max(0, -1) = 0`, `Math.max(0, 5) = 5`. Can you show a sample document, please? – Val Feb 24 '20 at 09:05
  • As I said I have price values between -1 and X. I want a query to ignore the values < 0 and only returns the minimum value of the positive prices. In your solution doc["price"].value is always -1; so Math.max(0, doc["price"].value) always returns 0. – Matin Hajatdoost Feb 24 '20 at 09:17
  • Is there any way to ignore the negative values first and after that pass it to min? – Matin Hajatdoost Feb 24 '20 at 09:20
  • Ok, then you simply need a query part that excludes documents with negative prices – Val Feb 24 '20 at 09:27
  • Can you show me how I can merge query part with my code? – Matin Hajatdoost Feb 24 '20 at 10:11
  • You should modify the `$this->query` part – Val Feb 24 '20 at 10:20