Elastica

A PHP client for elasticsearch.

Fork me on GitHub

Terms Aggregation

In JSON form, a terms aggregation looks like so:

1
2
3
4
5
6
7
8
{
    "aggs" : {
        "genders" : {
            "terms" : { "field" : "gender" },
            "size": 10
        }
    }
}

The same aggregation can be performed using Elastica:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
use Elastica\Aggregation\Terms;
use Elastica\Query;

// set up the aggregation
$termsAgg = new Terms("genders");
$termsAgg->setField("gender");
$termsAgg->setSize(10);

// add the aggregation to a Query object
$query = new Query();
$query->addAggregation($termsAgg);

// retrieve the results
$index = $elasticaClient->getIndex('someindex');
$buckets = $index->search($query)->getAggregation("genders");

Sub-aggregations are also supported:

1
2
3
4
5
6
7
8
9
10
11
12
13
{
    "aggs" : {
        "genders" : {
            "terms" : {
                "field" : "gender",
                "order" : { "height_stats.avg" : "desc" }
            },
            "aggs" : {
                "height_stats" : { "stats" : { "field" : "height" } }
            }
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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
}