has_child クエリでマッチした child の個数は、そのままだと取得できない
Published: 2022/3/8
Elasticsearch で has_child を使っている場合、大体は、 has_child
の query
に child についての条件を付与している場合が多い。
例
{
"query": {
"bool": {
"must": [
{
"has_child": {
"type": "child",
"query": {
// child conditions
}
}
},
// other parent conditions
]
},
}
}
そうすると、例えば最終結果における child の個数を知りたい時や、 aggregation を行いたいときなどが出てくるが、これはどうやったら良いのかが自明ではなかったのでメモ。
https://discuss.elastic.co/t/get-children-count-using-has-child-query/18939
ネットでいろいろ調べた結果、上記のような記事のみがヒットする。
具体的には、 has_child
を行っているクエリ自身の aggregation ではなく、別のクエリを用意して、そこで論理的に同じ条件を、 has_parent
で記述し、つまり、 child を主体としたクエリを発行して、 hit 件数の取得や、 aggregation を行うのが良いっぽい。
例えば上記の例で言えば、以下のような形になるはず。
{
"query": {
"bool": {
"must": [
{
"has_parent": {
"type": "parent",
"query": {
// other parent conditions
}
}
},
// other child conditions
]
}
}
}
そして、そういったデータを同時に取得したい場合には、 msearch などを実行すれば良さそう。
Tags: elasticsearch
関連記事
Elasticsearch で join フィールドの値でフィルタする方法
2022/1/10
Elasticsearch-rails で接続先情報を設定する方法
2021/12/18
Elasticsearch のサーバー上でクエリログを出力する方法
2021/12/15