首页 > 解决方案 > 在嵌套查询中过滤聚合

问题描述

通过这个查询,我确定了最常用的类别。我想获取我识别的情绪值大于 0 的类别的数量。

[
    'aggs' => [
        'category_sentiment' => [
            [
                'nested' => [
                    'path' => 'entities.categories'
                ],
                'aggs' => [
                    'buckets' => [
                        'terms' => [
                            'field' => 'entities.categories.category',
                            'size' => 100
                        ],
                        'aggs' => [
                            'pos' => [
                                'filter' => [
                                    'range' => [
                                        'sentiment_score' => [ 'gt' => 0 ]
                                    ]
                                ]
                            ]
                        ]
                    ]
                ]
            ]
        ]
    ]
]

我得到的结果

            "category_sentiment": {
                "doc_count": 8424,
                "buckets": {
                    "doc_count_error_upper_bound": 0,
                    "sum_other_doc_count": 0,
                    "buckets": [
                        {
                            "key": "Category 1",
                            "doc_count": 6614,
                            "pos": {
                                "doc_count": 0
                            }
                        },
                        {
                            "key": "Category 2",
                            "doc_count": 1217,
                            "pos": {
                                "doc_count": 0
                            }
                        },
                        {
                            "key": "Category 3",
                            "doc_count": 422,
                            "pos": {
                                "doc_count": 0
                            }
                        }
                    ]
                }
            },

所有成分都有情绪值。但是,结果返回 0。

标签: elasticsearch

解决方案


因此,根据您的查询,您希望汇总嵌套查询中的内容。

现在,根据情绪得分的位置,您要么必须使用嵌套位置

'range' => ['entities.categories.sentiment_score' => [ 'gt' => 0 ]]

否则你将不得不反向嵌套备份链

    "aggs": {
    "to_ent":  :{
    # EITHER :
    "reverse_nested":{ } # to go to the top level 
    
    "reverse_nested":{ "entities" } # to go to entities level
    }
   }

然后您可以根据需要继续进行 aggs。

如果您提供示例,我将更新示例。


推荐阅读