Hi,
Sorry for the late reply, it took me some time to wrap my head around this as well. My initial idea with the script sort was misleading because, as you saw, acessing nested fields from the parent document context in scripts is not possible. The simplest solution in your case would be to (ab)use the score_mode of the nested query, which lets you control how matching nested docs affect the score of the parent. Since your range query is already in a filter, all matching nested docs have score 1 and by setting score_mode to sum you can get the count of all matching documents.
Also, if you only want to retrieve only the matching nested documents for your range, you can also use the nested inner_hits part. That way, the "inner_hits" section for each parent document should only contain the comments matching your range:
GET /posts/_search
{
"query": {
"nested": {
"path": "comments",
"filter": {
"range": {
"comments.date": {
"gte": "2014-10-01",
"lt": "2014-11-01"
}
}
},
"score_mode": "sum",
"inner_hits" : {}
}
}
}