How to filter buckets based on the comparison of two sub-aggregation metrics in ElasticSearch (python)?

My index has documents with the following fields: user_id, user_name, post_text, post_sentiment where post_sentiment is of type double, and represents the sentiment of the post. A post_sentiment greater than 0 indicates it is a happy post, while a post_sentiment lesser than 0 indicates a sad post.

I am trying to retrieve the users who have more happy posts than sad posts. I am using the Elasticsearch high-level python library.

I have created the following function, which seems correct to me logically. However, running it yields Error message: TransportError(500, 'search_phase_execution_exception'). I have made sure the problem is not with the connection or the index, but in fact with the query structure. Please indicate what I might be doing wrong here.

def users_more_sentiment_posts(search_object: Search):
    a = search_object.aggs.bucket(
            "users",
            "terms",
            field="user_id"
        ).metric(
            "positive_post_count_per_bucket",
            "range", 
            field="post_sentiment", 
            ranges= [{'from': 0.0}]
        ).metric(
            "negative_post_count_per_bucket",
            "range", 
            field="post_sentiment", 
            ranges= [{'to': 0.0}]
        ).pipeline(
            "happy_posts",
            "bucket_selector",
            buckets_path={
                "positiveCount": "positive_post_count_per_bucket._count",
                "negativeCount": "negative_post_count_per_bucket._count"
            },
            script="params.positiveCount > params.negativeCount"
        ).bucket(
            "posts",
            "top_hits",
            size=10
        )

    response = search_object.execute()

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.