'Elasticsearch foselastica repository and groupBy
Hello I have a problem..
I have my elastica repository
namespace XX\xxx;
use FOS\ElasticaBundle\Repository;
class TestRepository extends Repository
{
public function getExamples($argOne, $argTwo) {
$query = new BoolQuery();
$matchOne = new Match();
$matchOne->setField('column_one', $argOne);
$query->addMust($matchOne);
$matchTwo = new Match();
$matchOne->setField('column_two', $argTwo);
$query->addMust($matchTwo);
return $this->find($query);
}
}
And mapping
...
types:
example:
mappings:
column_one:
type: integer
column_two:
type: string
column_three:
type: date
My problem is..
I need to get query group by column three. And I have no idea how to do this.
I'll be grateful for the informations..
Solution 1:[1]
You need to use Aggregations.
Example:
use Elastica\Aggregation\Terms;
use Elastica\Query;
// set up the aggregation
$termsAgg = new Terms("dates");
$termsAgg->setField("column_three");
$termsAgg->setSize(10);
// add the aggregation to a Query object
$query = new Query();
$query->addAggregation($termsAgg);
$index = $elasticaClient->getIndex('someindex');
$buckets = $index->search($query)->getAggregation("dates");
foreach($buckets as $bucket){
$statsAggResult = $bucket["column_three"];
// do something with the result of the stats agg
}
Read more here: http://elastica.io/example/aggregations/terms.html
Solution 2:[2]
Yes, but here's problem.
How to read this data? I search about this and i found methos search(). It return SetResults with method getAggregations().
But.. this is repository.. there is method find() returns array...
How get I aggregations in this case?
Solution 3:[3]
Terms Aggregation
From https://elastica.io/example/aggregations/terms.html
use Elastica\Aggregation\Terms;
use Elastica\Aggregation\Stats;
use Elastica\Query;
$termsAgg = new Terms("genders");
$termsAgg->setField("gender");
$termsAgg->setOrder("height_stats.avg", "desc");
$statsAgg = new Stats("height_stats");
$statsAgg->setField("height");
$termsAgg->addAggregation($statsAgg);
$index = $elasticaClient->getIndex('someindex');
$buckets = $index->search($query)->getAggregation("genders");
foreach($buckets as $bucket){
$statsAggResult = $bucket["height_stats"];
// do something with the result of the stats agg
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Jack Red |
| Solution 3 | Mohammad.Trabelsi |
