Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elasticsearch: has_child query with children aggregation - bucket counts are wrong

I'm attempting to find parents based on matches in their children and retrieve children term aggregations for the matches. For some reason, the bucket count for the children aggregation is showing a higher count than actual results (I would be happy if it showed the count of the parents - or the children - in the particular children bucket).

The query is similar to the following (NOTE: I use the filtered query as I will later add a filter in addition to the query):

{
"query" : {
    "filtered" : {
        "query" : {
            "has_child" : {
            "type" : "blog_tag",
            "query" : {
                "filtered" : {
                    "query" : {
                        "term" : {
                            "tag" : "something"
                        }
                    }
                }
            }
        }
    }
},
"aggs" : {
    "my_children" : {
        "children" : {
            "type" : "my_child_type"
        },
        "aggs" : {
            "field_name" : {
                "terms" : {
                    "field" : { "blog.blog_tag.field_name" }
                }
            }
        }
    }
}     

}

What is the correct way to do this?

like image 466
windup Avatar asked Mar 15 '23 02:03

windup


1 Answers

The problem was as noted in the comments. The solution was to filter the aggregation with the query,

"query" : {
    "filtered" : {
        "query" : {
            "has_child" : {
            "type" : "blog_tag",
            "query" : {
                "filtered" : {
                    "query" : {
                        "term" : {
                            "tag" : "something"
                        }
                    }
                }
            }
        }
    }
},
"aggs" : {
    "my_children" : {
        "children" : {
            "type" : "my_child_type"
        },
        "aggs" : {
            "results" : {
                "filter" : {
                    "query" : {
                        "filtered" : {
                            "query" : {
                                "term" : {
                                    "tag" : "something"
                                }
                            }
                        }
                    }
                },
                "aggs" : {
                    "field_name" : {
                        "terms" : {
                            "field" : { "blog.blog_tag.field_name" }
                       }
                    }
                }
            }
        }
    }
}
like image 132
windup Avatar answered May 08 '23 10:05

windup