1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Elastica\Test\Aggregation; |
4
|
|
|
|
5
|
|
|
use Elastica\Aggregation\ExtendedStats; |
6
|
|
|
use Elastica\Document; |
7
|
|
|
use Elastica\Index; |
8
|
|
|
use Elastica\Query; |
9
|
|
|
|
10
|
|
|
/** |
11
|
|
|
* @internal |
12
|
|
|
*/ |
13
|
|
|
class ExtendedStatsTest extends BaseAggregationTest |
14
|
|
|
{ |
15
|
|
|
/** |
16
|
|
|
* @group functional |
17
|
|
|
*/ |
18
|
|
|
public function testExtendedStatsAggregation(): void |
19
|
|
|
{ |
20
|
|
|
$agg = new ExtendedStats('stats'); |
21
|
|
|
$agg->setField('price'); |
22
|
|
|
|
23
|
|
|
$query = new Query(); |
24
|
|
|
$query->addAggregation($agg); |
25
|
|
|
$results = $this->_getIndexForTest()->search($query)->getAggregation('stats'); |
26
|
|
|
|
27
|
|
|
$this->assertEquals(4, $results['count']); |
28
|
|
|
$this->assertEquals(1, $results['min']); |
29
|
|
|
$this->assertEquals(8, $results['max']); |
30
|
|
|
$this->assertEquals((5 + 8 + 1 + 3) / 4.0, $results['avg']); |
31
|
|
|
$this->assertEquals((5 + 8 + 1 + 3), $results['sum']); |
32
|
|
|
$this->assertArrayHasKey('sum_of_squares', $results); |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
/** |
36
|
|
|
* @group functional |
37
|
|
|
*/ |
38
|
|
View Code Duplication |
public function testExtendedStatsAggregationWithMissing(): void |
|
|
|
|
39
|
|
|
{ |
40
|
|
|
$agg = new ExtendedStats('stats'); |
41
|
|
|
$agg->setField('price'); |
42
|
|
|
$agg->setMissing(10); |
43
|
|
|
|
44
|
|
|
$query = new Query(); |
45
|
|
|
$query->addAggregation($agg); |
46
|
|
|
$results = $this->_getIndexForTest()->search($query)->getAggregation('stats'); |
47
|
|
|
|
48
|
|
|
$this->assertEquals(5, $results['count']); |
49
|
|
|
$this->assertEquals(1, $results['min']); |
50
|
|
|
$this->assertEquals(10, $results['max']); |
51
|
|
|
$this->assertEquals((5 + 8 + 1 + 3 + 10) / 5.0, $results['avg']); |
52
|
|
|
$this->assertEquals((5 + 8 + 1 + 3 + 10), $results['sum']); |
53
|
|
|
$this->assertArrayHasKey('sum_of_squares', $results); |
54
|
|
|
} |
55
|
|
|
|
56
|
|
View Code Duplication |
protected function _getIndexForTest(): Index |
|
|
|
|
57
|
|
|
{ |
58
|
|
|
$index = $this->_createIndex(); |
59
|
|
|
|
60
|
|
|
$index->addDocuments([ |
61
|
|
|
new Document(1, ['price' => 5]), |
62
|
|
|
new Document(2, ['price' => 8]), |
63
|
|
|
new Document(3, ['price' => 1]), |
64
|
|
|
new Document(4, ['price' => 3]), |
65
|
|
|
new Document(5, []), |
66
|
|
|
]); |
67
|
|
|
|
68
|
|
|
$index->refresh(); |
69
|
|
|
|
70
|
|
|
return $index; |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.