Distinct and GroupBy
This content is for v3.9. Switch to the latest version for up-to-date documentation.
For this Elasticsearch implementation, the distinct()
and groupBy()
methods are interchangeable and will yield the same results.
Basic Usage
The distinct()
and groupBy()
methods are used to retrieve unique values of a given field.
Distinct
Retrieves unique user_ids of users logged in the last 30 days
GroupBy
Retrieves unique user_ids of users logged in the last 30 days
Working with Collections
The results from distinct()
and groupBy()
queries are returned as collections, enabling the use of Laravel’s rich collection methods for further manipulation or processing.
Loads the related user data for the distinct user_ids
Multiple Fields Aggregation
The distinct()
and groupBy()
methods can be used to retrieve unique values of multiple fields.
Retrieves unique user_ids and log_titles of users logged in the last 30 days, example:
Ordering by Aggregation Count
Sorting the results based on the count of aggregated fields or the distinct values themselves can provide ordered insights into the data.
Retrieves unique user_ids of users logged in the last 30 days, ordered by the count of logs in ascending order
You can also order by the distinct values themselves:
Retrieves unique user_ids of users logged in the last 30 days, ordered by the user_id ascending
Returning Count values with Distinct Results
To include the count of distinct values alongside the results, use distinct(true)
. This can be invaluable for analytics and reporting purposes.
Retrieves unique user_ids of users logged in the last 30 days, with the count of logs ordered by the count in descending order. Example result: