Error while performing distinct query on elasticsearch


I am trying to run the following search on Elasticsearch

GET /users/doc/_search
{
  "size": 0, 
  "aggs": {
    "distinct_ages": {
      "terms": {
        "field": "Age",
        "size": 1000
      }
    }
  }
}

and i am getting following exception

{
  "error": {
    "root_cause": [
      {
        "type": "illegal_argument_exception",
        "reason": "Fielddata is disabled on text fields by default. Set fielddata=true on [Age] in order to load fielddata in memory by uninverting the inverted index. Note that this can however use significant memory. Alternatively use a keyword field instead."
      }
    ],
    "type": "search_phase_execution_exception",
    "reason": "all shards failed",
    "phase": "query",
    "grouped": true,
    "failed_shards": [
      {
        "shard": 0,
        "index": "users",
        "node": "E23kjhdaegjnTskadh3W84xfumsyg",
        "reason": {
          "type": "illegal_argument_exception",
          "reason": "Fielddata is disabled on text fields by default. Set fielddata=true on [Age] in order to load fielddata in memory by uninverting the inverted index. Note that this can however use significant memory. Alternatively use a keyword field instead."
        }
      }
    ],
    "caused_by": {
      "type": "illegal_argument_exception",
      "reason": "Fielddata is disabled on text fields by default. Set fielddata=true on [Age] in order to load fielddata in memory by uninverting the inverted index. Note that this can however use significant memory. Alternatively use a keyword field instead.",
      "caused_by": {
        "type": "illegal_argument_exception",
        "reason": "Fielddata is disabled on text fields by default. Set fielddata=true on [Age] in order to load fielddata in memory by uninverting the inverted index. Note that this can however use significant memory. Alternatively use a keyword field instead."
      }
    }
  },
  "status": 400
}

1 Answer

6 years ago by

Add .keyword to your field name i.e use the following query

GET /users/doc/_search
{
  "size": 0, 
  "aggs": {
    "distinct_ages": {
      "terms": {
        "field": "Age.keyword",
        "size": 1000
      }
    }
  }
}
6 years ago by Karthik Divi