Elasticsearch - 过滤并获得每次命中的匹配结果
Elasticsearch - filter and get matched results per hit
在 elasticsearch 中,我想根据聚合过滤查询,并在聚合值小于 X 的地方过滤我的结果。类似于 sql 中的查询。
我在 elasticsearch 中有一些测试数据,看起来像这样。
[
{
"user_id" : 1,
"brand" : "Renault"
},
{
"user_id" : 2,
"brand" : "Renault"
},
{
"user_id" : 1,
"brand" : "Renault"
},
{
"user_id" : 2,
"brand" : "Ford"
}
]
user_id 是我想用于聚合的关键。
使用 mysql,它会类似于
SELECT count(*) as matching, user_id from some_table where brand = 'Renault' HAVING COUNT(*) >= 2 GROUP BY user_id
这可以使用 elasticsearch 吗?
使用Filter Aggregation
and Terms Aggregation
即可实现。
{
"aggs": {
"users_owning_renault": {
"filter": {
"term": {
"brand": "renault"
}
},
"aggs": {
"users": {
"terms": {
"field": "user_id",
"min_doc_count": 2,
"size": 0
}
}
}
}
}
}
以您提到的示例文档为例,响应如下所示:
{
...
"aggregations": {
"users_owning_renault": {
"doc_count": 3,
"users": {
"buckets": [
{
"key": 1,
"doc_count": 2
}
]
}
}
}
}
这里,key
是user_id
,doc_count
是matching
。当多个用户满足搜索条件时,相应的整体将添加到buckets
数组中。
在 elasticsearch 中,我想根据聚合过滤查询,并在聚合值小于 X 的地方过滤我的结果。类似于 sql 中的查询。
我在 elasticsearch 中有一些测试数据,看起来像这样。
[
{
"user_id" : 1,
"brand" : "Renault"
},
{
"user_id" : 2,
"brand" : "Renault"
},
{
"user_id" : 1,
"brand" : "Renault"
},
{
"user_id" : 2,
"brand" : "Ford"
}
]
user_id 是我想用于聚合的关键。 使用 mysql,它会类似于
SELECT count(*) as matching, user_id from some_table where brand = 'Renault' HAVING COUNT(*) >= 2 GROUP BY user_id
这可以使用 elasticsearch 吗?
使用Filter Aggregation
and Terms Aggregation
即可实现。
{
"aggs": {
"users_owning_renault": {
"filter": {
"term": {
"brand": "renault"
}
},
"aggs": {
"users": {
"terms": {
"field": "user_id",
"min_doc_count": 2,
"size": 0
}
}
}
}
}
}
以您提到的示例文档为例,响应如下所示:
{
...
"aggregations": {
"users_owning_renault": {
"doc_count": 3,
"users": {
"buckets": [
{
"key": 1,
"doc_count": 2
}
]
}
}
}
}
这里,key
是user_id
,doc_count
是matching
。当多个用户满足搜索条件时,相应的整体将添加到buckets
数组中。