Filtering nested objects using inner hits total

I'm new to Elasticsearch so forgive me if I don't know the lingo.

I have this mapping with a nested object Command

"Command": { "type": "nested", "include_in_parent": true, "properties": { "Src": { "type": "string", "index": "not_analyzed" }, "Dst": { "type": "string", "index": "not_analyzed" }, "CommandName": { "type": "string", "index": "not_analyzed" }, "Time": { "type": "string", "index": "not_analyzed" }, "Action": { "type": "string", "index": "not_analyzed" }, } }, "OsInfo": { "type": "string", "index": "not_analyzed" }, "OsRev": { "type": "string", "index": "not_analyzed" }, "OsUID": { "type": "string", "index": "not_analyzed" }, "Osname": { "type": "string", "index": "not_analyzed" },

I have a query
{ "query": { "filtered": { "query": { "bool": { "must": [ {"nested": { "path": "Command", "query": { "bool": { "must": [ {"match": {"Command.Action": "Create"}} ] } }, "inner_hits": { "size": 20, "_source": ["Action"] }, "score_mode": "sum" } } ] } } } } }

which gives me 20 inner hits (with only the Action field) sorted from most inner hits to least per outer hit

My question is how do i filter the outer hits based on the amount of inner hits?
For example:
I want all the outer docs that have exactly 4 inner hits from Command.Action:Create

Thanks!
Jeremy

This isn't possible with inner_hits. However it is possible to do this by wrapping the nested query's inner query in a constant_score query with a boost of 1 (add a score of 1 per nested document) and wrapping the nested query into a function_score query and only allowing top level hits with a score of 4:

{
  "query": {
    "bool": {
      "must": [
        {
          "function_score": {
            "query": {
              "nested": {
                "path": "Command",
                "query": {
                  "constant_score": {
                    "query": {
                      "match": {
                        "Command.Action": "Create"
                      }
                    },
                    "boost": 1
                  }
                },
                "score_mode": "sum",
                "inner_hits": {
                  "size": 20,
                  "_source": [
                    "Action"
                  ]
                }
              }
            },
            "min_score" : 4
          }
        }
      ]
    }
  }
}

Note: I'm not sure what ES version you're using, but this query does assume a 2.x version.

Thanks for the answer! This only gives a lower bound for the inner hits though.. is there a max_score that I could use to set an upper bound as well or an exact_score to find all docs with the exact amount?

Thanks!

Jeremy