问题
If I have a bunch of documents in elaticsearch that I want to be returned grouped by the one field of the document, how do I do it? Also I need it to consistently return a fixed number of results (using set maxresults)
For example if I have a bunch of documents each document representing a person and fields of the document containing attributes of the person. Let's say each person has a city field in the document. I would like to query Elasticsearch in a way that will return 50 results that are grouped by city. By 50 results I want to know how it is possible to return 50 cities mapped to all the people in those cities.
I found an implementation in:
http://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-metrics-top-hits-aggregation.html
But i want to apply pagination to these results as well. I dont see a setOffset and setLimit possibility in ES. Ideas?
回答1:
how it is possible to return 50 cities mapped to all the people in those cities.
Query you are looking for looks like this:
curl -XGET 'http://localhost:9200/users/user/_search?pretty' -d '{
"aggs": {
"users-by-city": {
"terms": {
"field": "city",
"size": 50
},
"aggs": {
"top_tag_hits": {
"top_hits": {
"from": 0,
"size": 9000
}
}
}
}
}
}'
In Elastica, equivalent query could be created this way:
$query = new Elastica\Query();
$qb = new Elastica\QueryBuilder();
$query->addAggregation(
$qb->aggregation()->terms('users-by-city')
->setField('city')
->setSize(50)
->addAggregation(
$qb->aggregation()->top_hits('top-hits-in-city')
->setFrom(0)
->setSize(9000)
)
);
If you want to paginate results, just change arguments passed into setFrom
and setSize
.
来源:https://stackoverflow.com/questions/29182791/how-do-i-group-documents-in-elasticsearch-by-a-single-field