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.
segmentSizenumberNoInternal candidate size used while collecting top terms.
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
  }
}