Get parents whose none of children matches

Hi,

having a parent doc_type A and children doc_type B. Is there a way to query "all the A documents where NONE/ALL of their Bs children matches some filters"?

Having:

A1
B1.foo = 200
B2.foo = 100
A2
B3. foo = 100

And this query:

{ "query": { "has_child": { "type": "B", "query": { "filtered": { "filter": { "bool": { "must_not": { "match": { "user_id": 200 }} } } } } } } }

I get both A1 and A2, since A1 has a child with foo != 200.

Thanks.

I accomplish this by going down another level of bool.

So in English, I say "Give me As that have children that do not have parents that have children that have Bs"

So you have to use the has_parent as well as the has_child.

It's a bit fiddly but it works.

Hi bw99, thanks for replying. Could you explain this with an example?

Thank you very much.

Oh, now I look at it, I think maybe you don't need what I said.

You just need to say (in pseudo code!)

query {
must not {
has child {
must {
{ "match": { "user_id": 200 }}
}
}
}
}

I think you're saying "Give me parents that have a child that doesn't have 200", whereas you need to be saying "Give me parents that do NOT have a child that DOES (must) have 200"

bw99, I thought has_child needed to work outside the must_not clause.

I need a query to get parents whose NONE of their children match a certain query. Also, a query to get parents whose ALL of their children match a certain query.

Finally we've modeled the data in order to not depend on this query, but it'd be interesting know if there is a way in ES to do this.

Thanks bw99.

bw99, I thought has_child needed to work outside the must_not clause.

I'm not sure what you mean. You can use boolean clauses nested several levels deep. So in pseudo code you're saying:

Give me all parents who
  must not have
    a child that
      must have 
        200

Not sure how you would do all (haven't needed to do that yet) - but I think the above should work for your first use case.