NGRAMS()

All functions > ARRAY > NGRAMS()

Returns adjacent n-element sub-sequences (n-grams) sliding across the input array.

Signatures

Returns: Sliding windows of length n

NGRAMS(array: ARRAY<T>, n: BIGINT) → ARRAY<ARRAY<T>>
sql
ParameterTypeRequiredDescription
arrayARRAY<T>YesInput array (scalar or ROW elements)
nBIGINTYesNumber of adjacent elements per n-gram

Notes

  • Each n-gram contains exactly n adjacent elements from the input (or the full array when n exceeds the array length)
  • Supports scalar arrays, arrays of rows (ARRAY<ROW(...)>), and nested arrays (ARRAY<ARRAY<T>>)
  • When n is larger than the array length, the result is a single n-gram containing the whole array
  • Returns an empty array only when the input array is empty
  • The n parameter must be a positive integer

See also

Examples

FeatureQL
SELECT
    -- Bigrams on strings
    f1 := NGRAMS(ARRAY('foo', 'bar', 'baz', 'foo'), 2),
    -- Trigrams on strings
    f2 := NGRAMS(ARRAY('foo', 'bar', 'baz', 'foo'), 3),
    -- Window spans full array
    f3 := NGRAMS(ARRAY('foo', 'bar', 'baz', 'foo'), 4),
    -- Window larger than array length
    f4 := NGRAMS(ARRAY('foo', 'bar', 'baz', 'foo'), 5),
    -- Bigrams on integers
    f5 := NGRAMS(ARRAY(1, 2, 3, 4), 2),
    -- Bigrams on rows from ZIP
    f6 := NGRAMS(ZIP(ARRAY(1, 2, 3) AS x, ARRAY('a', 'b', 'c') AS y), 2)
;
Result
f1 ARRAYf2 ARRAYf3 ARRAYf4 ARRAYf5 ARRAYf6 ARRAY
[[foo, bar], [bar, baz], [baz, foo]][[foo, bar, baz], [bar, baz, foo]][[foo, bar, baz, foo]][[foo, bar, baz, foo]][[1, 2], [2, 3], [3, 4]][[{x: 1, y: a}, {x: 2, y: b}], [{x: 2, y: b}, {x: 3, y: c}]]

Last update at: 2026/06/20 10:08:10