2
votes

I have documents with a nested field that looks like this:

...
"results": [
  {
    "id": "1234",
    "name": "asdf"
  },
  {
    "id": "5678",
    "name": "jklö"
  }
],
"ip": "1.2.3.4"
...

The mapping for the nested field looks like this:

"results": {
  "type": "nested",
  "properties": {
    "id": {
      "type": "string"
    },
    "name": {
      "type": "string"
    }
  }
}

Before I switched to elasticsearch 2 I had a query with aggs that counted the documents that had no results. Here's the aggregation part of the query:

"aggs": {
  "no_result": {
    "filter": {
      "missing": {
        "field": "results"
      }
    },
    "aggs": {
      "count": {
        "value_count": {
          "field": "ip"
        }
      }
    }
  }
}

Now that I switched to elasticserach 2 it just counts all documents. I already tried different things like counting all documents and counting results so that I can subtract the results but

"aggs": {
  "results_count": {
    "value_count": {
      "field": "results"
    }
  }
}

Is always 0

How can I correctly filter/count my nested fields?

2

2 Answers

3
votes

if you want to count the number of documents which have results you can do this.

{
  "size": 0,
  "aggs": {
    "count": {
      "nested": {
        "path": "results"
      },
      "aggs": {
        "top_reverse_nested": {
          "reverse_nested": {}
        }
      }
    }
  }
}

the number count will be in top_reserve_nested doc_count

0
votes

"field": "ip"

should be "field": "id"