|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Elastica\Test\Aggregation; |
| 4 | + |
| 5 | +use Elastica\Aggregation\Sampler; |
| 6 | +use Elastica\Aggregation\Sum; |
| 7 | +use Elastica\Document; |
| 8 | +use Elastica\Index; |
| 9 | +use Elastica\Query; |
| 10 | + |
| 11 | +class SamplerTest extends BaseAggregationTest |
| 12 | +{ |
| 13 | + protected function _getIndexForTest(): Index |
| 14 | + { |
| 15 | + $index = $this->_createIndex(null, true, 2); |
| 16 | + |
| 17 | + $routing1 = 'first_routing'; |
| 18 | + $routing2 = 'second_routing'; |
| 19 | + |
| 20 | + $index->addDocuments([ |
| 21 | + (new Document(1, ['price' => 5]))->setRouting($routing1), |
| 22 | + (new Document(2, ['price' => 8]))->setRouting($routing1), |
| 23 | + (new Document(3, ['price' => 1]))->setRouting($routing1), |
| 24 | + (new Document(4, ['price' => 3]))->setRouting($routing2), |
| 25 | + (new Document(5, ['price' => 1.5]))->setRouting($routing2), |
| 26 | + ]); |
| 27 | + |
| 28 | + $index->refresh(); |
| 29 | + |
| 30 | + return $index; |
| 31 | + } |
| 32 | + |
| 33 | + /** |
| 34 | + * @group unit |
| 35 | + */ |
| 36 | + public function testToArray() |
| 37 | + { |
| 38 | + $expected = [ |
| 39 | + 'sampler' => [ |
| 40 | + 'shard_size' => 1, |
| 41 | + ], |
| 42 | + 'aggs' => [ |
| 43 | + 'price_sum' => [ |
| 44 | + 'sum' => [ |
| 45 | + 'field' => 'price', |
| 46 | + ], |
| 47 | + ], |
| 48 | + ], |
| 49 | + ]; |
| 50 | + |
| 51 | + $agg = new Sampler('price_sampler'); |
| 52 | + $agg->setShardSize(1); |
| 53 | + |
| 54 | + $childAgg = new Sum('price_sum'); |
| 55 | + $childAgg->setField('price'); |
| 56 | + |
| 57 | + $agg->addAggregation($childAgg); |
| 58 | + |
| 59 | + $this->assertEquals($expected, $agg->toArray()); |
| 60 | + } |
| 61 | + |
| 62 | + /** |
| 63 | + * @dataProvider shardSizeProvider |
| 64 | + * @group functional |
| 65 | + * |
| 66 | + * @param int $shardSize |
| 67 | + * @param int $docCount |
| 68 | + */ |
| 69 | + public function testSamplerAggregation(int $shardSize, int $docCount) |
| 70 | + { |
| 71 | + $agg = new Sampler('price_sampler'); |
| 72 | + $agg->setShardSize($shardSize); |
| 73 | + |
| 74 | + $childAgg = new Sum('price_sum'); |
| 75 | + $childAgg->setField('price'); |
| 76 | + |
| 77 | + $agg->addAggregation($childAgg); |
| 78 | + |
| 79 | + $query = new Query(); |
| 80 | + $query->addAggregation($agg); |
| 81 | + $results = $this->_getIndexForTest()->search($query)->getAggregation('price_sampler'); |
| 82 | + |
| 83 | + $this->assertEquals($docCount, $results['doc_count']); |
| 84 | + } |
| 85 | + |
| 86 | + public function shardSizeProvider() |
| 87 | + { |
| 88 | + return [ |
| 89 | + [1, 2], |
| 90 | + [2, 4], |
| 91 | + [3, 5], |
| 92 | + ]; |
| 93 | + } |
| 94 | +} |
0 commit comments