How to get distinct terms from multiple fields

I need to get distinct cities from multiple fields using aggregations.

{
    "originCity": "Moscow"
    "destCity": "Stockholm"
}

Thanks

I'd define a copy_to parameter for each of those fields in the mapping, so at index time it will copy the content of originCity and destCity to a keyword field you can name city. Then run a Terms agg on city is straightforward.

Thanks @dadoonet

I have tried copy_to example from the documentation as below.

PUT my_index
{
  "mappings": {
    "_doc": {
      "properties": {
        "first_name": {
          "type": "text",
          "copy_to": "full_name" 
        },
        "last_name": {
          "type": "text",
          "copy_to": "full_name" 
        },
        "full_name": {
          "type": "text"
        }
      }
    }
  }
}

PUT my_index/_doc/1
{
  "first_name": "John",
  "last_name": "Smith"
} 

Now tried terms aggregation, but didn't get the result as expected.

GET /my_index/_doc/_search
{ "size": 0,
  "aggs": {
    "NAME": {
      "terms": {
        "field": "full_name.keyword",
        "size": 10
      }
    }
  }
}


Ouput:

{
  "took": 1,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "skipped": 0,
    "failed": 0
  },
  "hits": {
    "total": 1,
    "max_score": 0,
    "hits": []
  },
  "aggregations": {
    "NAME": {
      "doc_count_error_upper_bound": 0,
      "sum_other_doc_count": 0,
      "buckets": []
    }
  }
}

There is no full_name.keyword in your mapping. I don't see how this can even run.

It should be something like:

PUT my_index
{
  "mappings": {
    "_doc": {
      "properties": {
        "first_name": {
          "type": "text",
          "copy_to": "full_name" 
        },
        "last_name": {
          "type": "text",
          "copy_to": "full_name" 
        },
        "full_name": {
          "type": "keyword"
        }
      }
    }
  }
}

PUT my_index/_doc/1
{
  "first_name": "John",
  "last_name": "Smith"
} 

GET /my_index/_doc/_search
{
 "size": 0,
  "aggs": {
    "NAME": {
      "terms": {
        "field": "full_name"
      }
    }
  }
}

Thanks very much @dadoonet :grinning:

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.