Skip to content

Commit f8f1efc

Browse files
committed
Merge pull request #728 from agallou/range_key
allow to customize the key on a range aggregation
2 parents c10b047 + d7e6a77 commit f8f1efc

File tree

2 files changed

+42
-4
lines changed

2 files changed

+42
-4
lines changed

lib/Elastica/Aggregation/Range.php

+7-2
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,11 @@ class Range extends AbstractSimpleAggregation
1515
* Add a range to this aggregation
1616
* @param int|float $fromValue low end of this range, exclusive (greater than)
1717
* @param int|float $toValue high end of this range, exclusive (less than)
18+
* @param string $key customized key value
1819
* @return Range
1920
* @throws \Elastica\Exception\InvalidException
2021
*/
21-
public function addRange($fromValue = null, $toValue = null)
22+
public function addRange($fromValue = null, $toValue = null, $key = null)
2223
{
2324
if (is_null($fromValue) && is_null($toValue)) {
2425
throw new InvalidException("Either fromValue or toValue must be set. Both cannot be null.");
@@ -30,6 +31,10 @@ public function addRange($fromValue = null, $toValue = null)
3031
if (!is_null($toValue)) {
3132
$range['to'] = $toValue;
3233
}
34+
if (!is_null($key)) {
35+
$range['key'] = $key;
36+
}
37+
3338
return $this->addParam('ranges', $range);
3439
}
3540

@@ -42,4 +47,4 @@ public function setKeyedResponse($keyed = true)
4247
{
4348
return $this->setParam('keyed', (bool)$keyed);
4449
}
45-
}
50+
}

test/lib/Elastica/Test/Aggregation/RangeTest.php

+35-2
Original file line numberDiff line numberDiff line change
@@ -37,5 +37,38 @@ public function testRangeAggregation()
3737

3838
$this->assertEquals(2, $results['buckets'][0]['doc_count']);
3939
}
40-
}
41-
40+
41+
42+
public function testRangeAggregationWithKey()
43+
{
44+
$agg = new Range("range");
45+
$agg->setField("price");
46+
$agg->addRange(null, 50, "cheap");
47+
$agg->addRange(50, 100, "average");
48+
$agg->addRange(100, null, "expensive");
49+
50+
$expected = array (
51+
'range' =>
52+
array (
53+
'field' => 'price',
54+
'ranges' =>
55+
array (
56+
array (
57+
'to' => 50,
58+
'key' => 'cheap',
59+
),
60+
array (
61+
'from' => 50,
62+
'to' => 100,
63+
'key' => 'average',
64+
),
65+
array (
66+
'from' => 100,
67+
'key' => 'expensive',
68+
),
69+
),
70+
),
71+
);
72+
73+
$this->assertEquals($expected, $agg->toArray());
74+
}}

0 commit comments

Comments
 (0)