Applies to VAST Cluster 5.5.
Functions › List, struct and map functions › Aggregate a list. Returns the sample excess kurtosis of the elements of a numeric list: how heavy the tails are compared with a normal distribution. It needs at least four non-NULL elements.
Syntax
list_kurtosis(l)
| Argument | Type | Description |
|---|---|---|
l |
a list of numbers | The values whose kurtosis is computed. |
Returns: DOUBLE.
Set up the examples
The examples connect with the ADBC driver, as in VAST Query Engine (ADBC), and work in a schema called docs_sql_fn_lists_list_kurtosis. Set QE_ENDPOINT, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY and VASTDB_BUCKET (SQL reference), and run the blocks in order in one Python session. Below each block is the output you should see.
This block connects, defines the run() and plan() helpers, and creates a table of five rows of lists: whole numbers (nums) and measurements (vals). Row 2 has a NULL element, row 3 has empty lists, row 4 has no values, and row 5's measurements are close to the largest DOUBLE:
import os
import re
import adbc_driver_manager
import adbc_driver_manager.dbapi as dbapi
import adbc_driver_vastdb
BUCKET = os.environ["VASTDB_BUCKET"]
SCHEMA = f'"{BUCKET}/docs_sql_fn_lists_list_kurtosis"'
conn = dbapi.connect(
driver=adbc_driver_vastdb.get_driver_path(),
db_kwargs={
"vast.db.endpoint": os.environ["QE_ENDPOINT"],
"vast.db.access_key": os.environ["AWS_ACCESS_KEY_ID"],
"vast.db.secret_key": os.environ["AWS_SECRET_ACCESS_KEY"],
},
autocommit=True,
)
def server_message(e):
"""The server's message in a driver error, without the request ID or the echoed statement."""
text = re.sub(r"\[req=0x[0-9a-f]+\]: ", "", str(e))
found = (re.search(r'message: "(.*?)", request_id', text, re.S)
or re.search(r"description: (.*)\)", text, re.S))
message = found.group(1) if found else text.strip().splitlines()[-1]
message = re.sub(r"^Plan query: '.*?' failed with: ", "", message, flags=re.S)
message = re.split(r"\\n|\n", message)[0].replace('\\"', '"')
return message.replace(BUCKET, "<bucket>")
def run(sql):
"""Run one statement. Print the rows it returns, or the error."""
try:
with conn.cursor() as cur:
cur.execute(sql)
rows = cur.fetchall() if cur.description else []
except (adbc_driver_manager.Error, OSError) as e:
print(f"{type(e).__name__}: {server_message(e)}")
else:
print(rows)
def plan(sql):
"""Print the plan without its ~N Rows lines: the table's row count, which can still be 0 just after an insert."""
with conn.cursor() as cur:
cur.execute("EXPLAIN " + sql)
steps = cur.fetchall()[0][1]
print("\n".join(line for line in steps.splitlines() if "Rows" not in line))
TABLE = f"{SCHEMA}.samples"
run(f"CREATE SCHEMA IF NOT EXISTS {SCHEMA}")
run(f"CREATE TABLE IF NOT EXISTS {TABLE} (id BIGINT, nums BIGINT[], vals DOUBLE[])")
run(f"INSERT INTO {TABLE} VALUES "
"(1, [1, 2, 3], [0.5, 2.5, -1.0]), "
"(2, [3, NULL, 3], [2.0, NULL]), "
"(3, [], []), "
"(4, NULL, NULL), "
"(5, [-5, 0, -5, 10], [1e308, 1e308, -1e-308])")
[]
[]
[(5,)]
What it does
list_kurtosis(l) measures the tails of the n non-NULL elements of l. It's the sample excess kurtosis: the fourth central moment divided by the square of the second, minus 3, then corrected for the sample size as ((n+1) × that + 6) × (n-1) / ((n-2)(n-3)).
- A normal distribution has an excess kurtosis of about 0. A positive result means more of the spread comes from a few far values; a negative one, that the values are spread more evenly.
[1.0, 2.0, 3.0, 10.0]gives3.227999999999999: the10.0stands far from the others.[1.0, 2.0, 3.0, 10.0, 11.0]gives-3.0410826680608927: two groups, no single far value.- Fewer than four non-NULL elements give NULL.
- Elements that are all the same give NULL.
For the population form, which needs fewer elements and has no correction, use list_kurtosis_pop.
NULLs and edge cases
| Input | Result |
|---|---|
NULL, or NULL::BIGINT[] |
NULL |
[]::DOUBLE[] (empty list) |
NULL |
[NULL, NULL]::DOUBLE[] |
NULL |
[1.0], [1.0, 2.0], [1.0, 2.0, 3.0] |
NULL (fewer than four elements) |
[5, 5, 5, 5] |
NULL |
[1.0, 2.0, 3.0, 10.0, 11.0] |
-3.0410826680608927 |
typeof(list_kurtosis([1, 2])) |
'DOUBLE' |
A number, string, BLOB, date or boolean |
Error: No function matches the given name and argument types, for example 'list_aggr(INTEGER_LITERAL, STRING_LITERAL)' |
The same cases, as the cluster returns them. They use the table and helpers from Set up the examples:
run("SELECT list_kurtosis(NULL), list_kurtosis(NULL::BIGINT[]), list_kurtosis([]::DOUBLE[]), "
"list_kurtosis([NULL, NULL]::DOUBLE[])")
run("SELECT list_kurtosis([1.0]), list_kurtosis([1.0, 2.0]), list_kurtosis([1.0, 2.0, 3.0]), list_kurtosis([5, 5, 5, 5])")
run("SELECT list_kurtosis([1.0, 2.0, 3.0, 10.0, 11.0]), typeof(list_kurtosis([1, 2]))")
run(f"SELECT list_kurtosis(123) FROM {TABLE} LIMIT 1")
[(None, None, None, None)]
[(None, None, None, None)]
[(-3.0410826680608927, 'DOUBLE')]
InternalError: Binder Error: No function matches the given name and argument types 'list_aggr(INTEGER_LITERAL, STRING_LITERAL)'. You might need to add explicit type casts.
Examples
The kurtosis of each row's numbers and measurements. Only row 5's numbers [-5, 0, -5, 10] have four elements; they give 1.5. Every other result is NULL, including all the measurements, which have at most three elements:
run(f"SELECT id, nums, list_kurtosis(nums), list_kurtosis(vals) FROM {TABLE} ORDER BY id LIMIT 10")
[(1, [1, 2, 3], None, None), (2, [3, None, 3], None, None), (3, [], None, None), (4, None, None, None), (5, [-5, 0, -5, 10], 1.5, None)]
The rows with a kurtosis to report:
run(f"SELECT id, nums FROM {TABLE} WHERE list_kurtosis(nums) IS NOT NULL ORDER BY id LIMIT 10")
[(5, [-5, 0, -5, 10])]
How it runs in VAST
The Query Engine runs on the cluster's CNodes, and a query on a table starts with a scan in VAST DataBase (VAST_SCAN). The scan reads a list column whole, and list_kurtosis() always runs in the Query Engine:
- In the
SELECTlist, a projection step computeslist_kurtosis()for each row the scan returns. - In
WHERE, the scan sends the list for every row, and aFILTERstep computeslist_kurtosis()and keeps the rows that match. No rows are skipped in storage.
The plan of the WHERE example shows the FILTER step above the scan:
plan(f"SELECT id FROM {TABLE} WHERE list_kurtosis(nums) IS NOT NULL")
┌───────────────────────────┐
│ PROJECTION │
│ ──────────────────── │
│ #1 │
│ │
└─────────────┬─────────────┘
┌─────────────┴─────────────┐
│ FILTER │
│ ──────────────────── │
│ (list_aggr(CAST(nums AS │
│ DOUBLE[]), 'kurtosis') IS│
│ NOT NULL) │
│ │
└─────────────┬─────────────┘
┌─────────────┴─────────────┐
│ VAST_SCAN │
│ ──────────────────── │
│ Function: VAST_SCAN │
│ │
│ Projections: │
│ nums │
│ id │
│ │
└───────────────────────────┘
Make it faster
- Add a condition on a plain column. A comparison of a column with a constant, such as
id > 1, is evaluated in VAST DataBase, solist_kurtosis()runs only on the rows that pass it. The plan forid > 1alone has noFILTERstep:
plan(f"SELECT id FROM {TABLE} WHERE id > 1")
┌───────────────────────────┐
│ VAST_SCAN │
│ ──────────────────── │
│ Function: VAST_SCAN │
│ Projections: id │
│ │
└───────────────────────────┘
- Store the kurtosis if you filter on it often. Compute it when you write the rows and keep it in its own column:
kurtosis > 1is pushed down,list_kurtosis(nums) > 1isn't.
Limitations and errors
- Short lists give NULL. With fewer than four non-NULL elements, the result is NULL rather than an error. Use list_kurtosis_pop for shorter lists.
- Lists only. Any other type fails with
No function matches the given name and argument types. The error nameslist_aggr, the list aggregate thatlist_kurtosisruns on, and its accepted formlist_aggr(ANY[], VARCHAR, [ANY...]) -> ANY. ORDER BYneeds aLIMIT. Without one, the query fails withThe operator 'ORDER_BY' type=1 is currently not supported for this usage.
Similar functions
| Function | What it computes | Fewest elements | Result for [1.0, 2.0, 3.0, 10.0]::DOUBLE[] |
|---|---|---|---|
list_kurtosis |
sample excess kurtosis | 4 | 3.227999999999999 |
| list_kurtosis_pop | population excess kurtosis, no sample-size correction | 2 | -0.7696000000000001 |
| list_skewness | sample skewness: asymmetry | 3 | 1.763632614803888 |
run("SELECT list_kurtosis(l), list_kurtosis_pop(l), list_skewness(l) FROM (SELECT [1.0, 2.0, 3.0, 10.0]::DOUBLE[] AS l)")
[(3.227999999999999, -0.7696000000000001, 1.763632614803888)]
Clean up:
run(f"DROP TABLE IF EXISTS {TABLE}")
run(f"DROP SCHEMA IF EXISTS {SCHEMA}")
conn.close()
[]
[]
See also
- List, struct and map functions: all the list functions.
- list_skewness: how lopsided a list's values are.
- Where filters run and pushdowns.
- EXPLAIN: how to read a plan.