Skip to content

Commit cb04930

Browse files
committed
Update 03-udf.md
1 parent 04de21a commit cb04930

File tree

1 file changed

+33
-1
lines changed

1 file changed

+33
-1
lines changed

docs/en/guides/54-query/03-udf.md

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,8 +57,11 @@ Embedded UDFs allow you to embed code written in the following programming langu
5757
- [JavaScript](#javascript)
5858
- [WebAssembly](#webassembly)
5959

60+
With Embedded UDFs, you can create both scalar functions and aggregate functions. Scalar functions operate on a single row of input and return a single value, while aggregate functions process multiple rows of input and return a single aggregated result, such as a sum or average.
61+
6062
:::note
61-
If your program content is large, you can compress it and then pass it to a stage. See the [Usage Examples](#usage-examples-2) for WebAssembly.
63+
- Creating aggregate UDFs with WebAssembly is not yet supported.
64+
- If your program content is large, you can compress it and then pass it to a stage. See the [Usage Examples](#usage-examples-2) for WebAssembly.
6265
:::
6366

6467
### Python (requires Databend Enterprise)
@@ -237,6 +240,35 @@ WHERE
237240
ORDER BY 1;
238241
```
239242

243+
This example defines an aggregate UDF that calculates the weighted average of a set of values by aggregating them based on their corresponding weights:
244+
245+
```sql
246+
CREATE FUNCTION weighted_avg (INT, INT) STATE {sum INT, weight INT} RETURNS FLOAT
247+
LANGUAGE javascript AS $$
248+
export function create_state() {
249+
return {sum: 0, weight: 0};
250+
}
251+
export function accumulate(state, value, weight) {
252+
state.sum += value * weight;
253+
state.weight += weight;
254+
return state;
255+
}
256+
export function retract(state, value, weight) {
257+
state.sum -= value * weight;
258+
state.weight -= weight;
259+
return state;
260+
}
261+
export function merge(state1, state2) {
262+
state1.sum += state2.sum;
263+
state1.weight += state2.weight;
264+
return state1;
265+
}
266+
export function finish(state) {
267+
return state.sum / state.weight;
268+
}
269+
$$;
270+
```
271+
240272
### WebAssembly
241273

242274
A WebAssembly UDF allows users to define custom logic or operations using languages that compile to WebAssembly. These UDFs can then be invoked directly within SQL queries to perform specific computations or data transformations.

0 commit comments

Comments
 (0)