How to unnest a 2d array into a 1d array quickly in PostgreSQL?

前端 未结 2 1516
孤街浪徒
孤街浪徒 2021-01-07 01:01

I have a really large array that have I computed with Apache Madlib and I would like to apply an operation to each single array in that 2d array.

I have found code t

2条回答
  •  再見小時候
    2021-01-07 01:08

    The function you found in my old answer does not scale well for big arrays. I never thought of arrays your size, which should probably be a set (a table) instead.

    Be that as it may, this plpgsql function replaces the one in the referenced answer. Requires Postgres 9.1 or later.

    CREATE OR REPLACE FUNCTION unnest_2d_1d(ANYARRAY, OUT a ANYARRAY)
      RETURNS SETOF ANYARRAY AS
    $func$
    BEGIN
       FOREACH a SLICE 1 IN ARRAY $1 LOOP
          RETURN NEXT;
       END LOOP;
    END
    $func$  LANGUAGE plpgsql IMMUTABLE STRICT;
    

    40x faster in my test on a big 2d-array in Postgres 9.6.

    STRICT to avoid an exception for NULL input (as commented by IamIC):

    ERROR: FOREACH expression must not be null

提交回复
热议问题