Skip to content

Instantly share code, notes, and snippets.

@sorenlouv
Last active September 21, 2023 14:53
Show Gist options
  • Save sorenlouv/3fd6b45938600401a2c30fa33ffdad1b to your computer and use it in GitHub Desktop.
Save sorenlouv/3fd6b45938600401a2c30fa33ffdad1b to your computer and use it in GitHub Desktop.
`_doc_count` example

Setup

PUT doc-count-fun

POST doc-count-fun/_doc
{
  "_doc_count": 10,
  "@timestamp": "2023-09-14T10:00:00.477Z"
}

POST doc-count-fun/_doc
{
  "_doc_count": 20,
  "@timestamp": "2023-09-15T10:00:00.477Z"
}

Search

GET doc-count-fun/_search
{
  "size": 0,
  "aggs": {
    "timeseries": {
      "date_histogram": {
        "field": "@timestamp",
        "fixed_interval": "1d"
      }
    }
  }
}

Response

{
  "took": 1,
  "timed_out": false,
  "_shards": {
    "total": 1,
    "successful": 1,
    "skipped": 0,
    "failed": 0
  },
  "hits": {
    "total": {
      "value": 2,
      "relation": "eq"
    },
    "max_score": null,
    "hits": []
  },
  "aggregations": {
    "timeseries": {
      "buckets": [
        {
          "key_as_string": "2023-09-14T00:00:00.000Z",
          "key": 1694649600000,
          "doc_count": 10
        },
        {
          "key_as_string": "2023-09-15T00:00:00.000Z",
          "key": 1694736000000,
          "doc_count": 20
        }
      ]
    }
  }
}

Getting the correct total

const docCounts = aggregations.timeseries.buckets.map(bucket => bucket.doc_count)
const total = _.sum(docCounts); // 30

Currently we are showing the total as 2 when the total should be 30 - or perhaps 2 hits (30 aggregated [?]), where the [?] is a tooltip for explaining this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment