elasticsearch/docs/reference/query-languages/esql/_snippets/functions
Nik Everett 45bfaab448
ESQL: ROUND_TO function (#128278)
Creates a `ROUND_TO` function that rounds it's input to one of the
provided values. Like so:
```
ROUND_TO(v, 0, 5000, 10000, 20000, 40000, 100000)

   v   | ROUND_TO
     0 | 0
   100 | 0
  6000 | 5000
 45001 | 40000
999999 | 100000
```

For some sequences of numbers you could do this with the `/` operator -
but for arbitrary sequences of numbers you needed `CASE` which is quite
slow. And hard to read!

Rewriting the example above would look like:
```
CASE (
  v <   5000,     0,
  v <  10000,  5000,
  v <  20000, 10000,
  v <  40000, 20000,
  v < 100000, 40000,
  100000
)
```

Even better, this is *fast*:
```
        (operation)  Mode  Cnt    Score   Error  Units
round_to_4_via_case  avgt    7  138.124 ± 0.738  ns/op
         round_to_4  avgt    7    0.805 ± 0.011  ns/op
         round_to_3  avgt    7    0.739 ± 0.011  ns/op
         round_to_2  avgt    7    0.651 ± 0.009  ns/op
         date_trunc  avgt    7    2.425 ± 0.018  ns/op
```

I've included a comparison to `DATE_TRUNC` above because we should be
able to rewrite `DATE_TRUNC` into `ROUND_TO` when we know the date range
of the index. This doesn't do it now, but it should be possible.
2025-05-23 10:14:30 -04:00
..
appendix ESQL: Document VALUES uniques (#128157) 2025-05-22 15:50:29 +02:00
description ESQL: ROUND_TO function (#128278) 2025-05-23 10:14:30 -04:00
examples ESQL: ROUND_TO function (#128278) 2025-05-23 10:14:30 -04:00
functionNamedParams ESQL: Claim transport version to backport #124913 (#127616) 2025-05-01 23:27:42 +02:00
layout ESQL: ROUND_TO function (#128278) 2025-05-23 10:14:30 -04:00
parameters ESQL: ROUND_TO function (#128278) 2025-05-23 10:14:30 -04:00
types ESQL: ROUND_TO function (#128278) 2025-05-23 10:14:30 -04:00