Skip to main content
$terms groups documents by distinct field values. Each distinct value becomes one bucket with its own docCount.

Compatibility

Field TypeSupported
TEXTNo
U64/I64/F64Yes
DATEYes
BOOLYes
KEYWORDYes
FACETNo
Field must be FAST.

Arguments

ArgumentTypeRequiredDescription
fieldstringYesField to bucket on.
sizenumberNoMax number of buckets returned.
segmentSizenumberNoNumber of candidate terms collected per index segment before merging. Raising it improves count accuracy at higher cost; lowering it is cheaper but less accurate. See Count accuracy.
showTermDocCountErrorbooleanNoInclude docCountErrorUpperBound in output.
minDocCountnumberNoBuckets with fewer docs are excluded.
orderobjectNoOne-key order object: { "count": "desc" }, { "key": "asc" }, or { "<subAggAlias>": "desc" }.
missingstring | numberNoBucket key used when the field is missing.
includestring | string[]NoInclude regex or explicit value list.
excludestring | string[]NoExclude regex or explicit value list.
await index.aggregate({
  aggregations: {
    by_category: {
      $terms: { field: "category", size: 5 },
    },
  },
});

Output

{
  "by_category": {
    "buckets": [
      { "key": "electronics", "docCount": 120 },
      { "key": "books", "docCount": 83 }
    ],
    "sumOtherDocCount": 42
  }
}
  • sumOtherDocCount is the number of matching documents that fell outside the returned buckets.

Count accuracy

$terms bucket counts are approximate. Terms are tallied per index segment and then merged, so a term’s docCount can be slightly off, especially for terms near the size cutoff.
docCountErrorUpperBound reports the maximum possible error on the returned counts (set showTermDocCountError: true for per-bucket values), and sumOtherDocCount is the number of matching documents not included in the returned buckets. Raising segmentSize reduces the error at the cost of more work per query. For an exact count of a specific term, use SEARCH.COUNT instead of reading it from a bucket.