Category: How do I do X?
Updated

This solution is summarized from an archived support forum post. This information may have changed. If you notice an error, please let us know in Discord.

Get List of Distinct Values From Existing Query Result Set

Issue

I have an Elasticsearch database query and I want to generate a list of unique values for a specific field. I tried using the "collapse" method but couldn't get it to work. I want to work with the existing results on the client-side and not re-run the query on the server.

Resolution

To generate a list of distinct values for the author_id field, two approaches can be used depending on your needs:

Using "terms" Aggregation:

  1. You can use Elasticsearch's "terms" aggregation to get a count of each unique author_id.
  2. This method requires adding an aggregation to your existing query. You need to add a "terms" key with a "field" key specifying the field you want distinct values for, in this case, author_id.
  3. Example of an Elasticsearch query with "terms" aggregation:

    {
      "aggs": {
        "distinct_author_ids": {
          "terms": {
            "field": "author_id"
          }
        }
      }
    }
    

This query will return an aggregation of distinct author_id values.

Using "Collapse" Method:

  • The "collapse" method can be used to collapse the search results based on the author_id field.
  • This approach groups the results by author_id, ensuring only one record is returned for each unique author_id.
  • Example of using the "collapse" method:

    {
      "query": {
        // Your existing query
      },
      "collapse": {
        "field": "author_id"
      }
    }