Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

allow to customize the key on a range aggregation #728

Merged
merged 1 commit into from
Nov 24, 2014
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions lib/Elastica/Aggregation/Range.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,11 @@ class Range extends AbstractSimpleAggregation
* Add a range to this aggregation
* @param int|float $fromValue low end of this range, exclusive (greater than)
* @param int|float $toValue high end of this range, exclusive (less than)
* @param string $key customized key value
* @return Range
* @throws \Elastica\Exception\InvalidException
*/
public function addRange($fromValue = null, $toValue = null)
public function addRange($fromValue = null, $toValue = null, $key = null)
{
if (is_null($fromValue) && is_null($toValue)) {
throw new InvalidException("Either fromValue or toValue must be set. Both cannot be null.");
Expand All @@ -30,6 +31,10 @@ public function addRange($fromValue = null, $toValue = null)
if (!is_null($toValue)) {
$range['to'] = $toValue;
}
if (!is_null($key)) {
$range['key'] = $key;
}

return $this->addParam('ranges', $range);
}

Expand All @@ -42,4 +47,4 @@ public function setKeyedResponse($keyed = true)
{
return $this->setParam('keyed', (bool)$keyed);
}
}
}
37 changes: 35 additions & 2 deletions test/lib/Elastica/Test/Aggregation/RangeTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,5 +37,38 @@ public function testRangeAggregation()

$this->assertEquals(2, $results['buckets'][0]['doc_count']);
}
}



public function testRangeAggregationWithKey()
{
$agg = new Range("range");
$agg->setField("price");
$agg->addRange(null, 50, "cheap");
$agg->addRange(50, 100, "average");
$agg->addRange(100, null, "expensive");

$expected = array (
'range' =>
array (
'field' => 'price',
'ranges' =>
array (
array (
'to' => 50,
'key' => 'cheap',
),
array (
'from' => 50,
'to' => 100,
'key' => 'average',
),
array (
'from' => 100,
'key' => 'expensive',
),
),
),
);

$this->assertEquals($expected, $agg->toArray());
}}