ElasticGraph Query API: Date Grouping
$ curl -s https://block.github.io/elasticgraph/dc.yml | docker compose -f - up --pull always
For Date fields, it’s generally more useful to group by truncated dates than by distinct raw values.
Here’s an example:
query AlbumSalesByReleaseYear {
artistAggregations {
nodes {
subAggregations {
albums {
nodes {
groupedBy {
releasedOn {
asDate(truncationUnit: YEAR)
}
}
aggregatedValues {
soldUnits {
exactSum
}
}
}
}
}
}
}
}
In this case, we’re truncating the Album.releaseOn dates to the year to give us one grouping per
year rather than one grouping per distinct date. The truncationUnit argument supports DAY, MONTH,
QUARTER, WEEK and YEAR values. In addition, an offset argument is supported, which can be used
to shift what grouping a Date falls into. This is particularly useful when using WEEK:
query AlbumSalesByReleaseWeek {
artistAggregations {
nodes {
subAggregations {
albums {
nodes {
groupedBy {
releasedOn {
asDate(truncationUnit: WEEK, offset: {amount: -1, unit: DAY})
}
}
aggregatedValues {
soldUnits {
exactSum
}
}
}
}
}
}
}
}
With no offset, grouped weeks run Monday to Sunday, but we can shift it using offset. In this case, the weeks have been
shifted to run Sunday to Saturday.
Finally, we can also group Date fields by what day of week they fall into using asDayOfWeek instead of asDate:
query AlbumSalesByReleaseDayOfWeek {
artistAggregations {
nodes {
subAggregations {
albums {
nodes {
groupedBy {
releasedOn {
asDayOfWeek
}
}
aggregatedValues {
soldUnits {
exactSum
}
}
}
}
}
}
}
}