You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/en/guides/54-query/03-udf.md
+33-1Lines changed: 33 additions & 1 deletion
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -57,8 +57,11 @@ Embedded UDFs allow you to embed code written in the following programming langu
57
57
-[JavaScript](#javascript)
58
58
-[WebAssembly](#webassembly)
59
59
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
+
60
62
:::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.
62
65
:::
63
66
64
67
### Python (requires Databend Enterprise)
@@ -237,6 +240,35 @@ WHERE
237
240
ORDER BY1;
238
241
```
239
242
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
+
CREATEFUNCTIONweighted_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
+
240
272
### WebAssembly
241
273
242
274
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