且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将Elasticsearch中的文档按单个字段分组?

更新时间:2022-12-11 20:52:38

如何能够返回映射到这些城市中所有人的50个城市.

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
                    }
                }
            }
        }
    }
}'

在Elastica中,可以通过以下方式创建等效查询:

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)
        )
);

如果要对结果进行分页,只需更改传递到setFromsetSize的参数.

If you want to paginate results, just change arguments passed into setFrom and setSize.