From: Grunthos (@Grunthos) <noreply+Grunthos@github.com>
To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>
Subject: [pgvector/pgvector] PR #966: Add support for sparsevec(int[], {real|double|int|numeric}[], int) to sparsevec
Date: Sun, 08 Mar 2026 11:02:33 +0000
Message-ID: <gh-pgvector-pgvector-966@github.com> (raw)
Creates a sparevec from binary data in arrays
Also added testbed cases and attempted to mimic exisiting coding style.
Performance comparison approximately 30x faster (or more) than array->text->sparsevec:
```
sparsevec constructor benchmark (N=100000 iterations)
A: input already available as text or array (conversion cost to sparsevec only)
C: starting from arrays via text intermediate (C1) vs direct constructor (C2)
Scenario n=10 n=100 n=500 n=1000 (n=number of entries in sparsevec) (ns/call)
-------------------- -------- -------- -------- --------
A1 text->sv 600 5423 27391 55141
A2 real[]->sv 197 707 2671 5678
A3 integer[]->sv 220 739 2869 6019
A4 float8[]->sv 300 733 3080 6018
A5 numeric[]->sv 752 6067 29451 59271
C1 arr->txt->sv 6081 26904 115771 227328
C2 arr->sv (direct) 220 706 2770 5563
-------------------- -------- -------- -------- --------
```
inline patch 1: sql/vector.sql, src/sparsevec.c, test/expected/sparsevec.out and 1 more (+284/-0 lines) download inline-1.patchdiff --git a/sql/vector.sql b/sql/vector.sqlindex 7fc36712b..2208f48a3 100644--- a/sql/vector.sql+++ b/sql/vector.sql@@ -736,6 +736,18 @@ CREATE FUNCTION l2_norm(sparsevec) RETURNS float8
CREATE FUNCTION l2_normalize(sparsevec) RETURNS sparsevec
AS 'MODULE_PATHNAME', 'sparsevec_l2_normalize' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
+CREATE FUNCTION sparsevec(int[], real[], int) RETURNS sparsevec+ AS 'MODULE_PATHNAME', 'sparsevec_coo' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;++CREATE FUNCTION sparsevec(int[], double precision[], int) RETURNS sparsevec+ AS 'MODULE_PATHNAME', 'sparsevec_coo' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;++CREATE FUNCTION sparsevec(int[], integer[], int) RETURNS sparsevec+ AS 'MODULE_PATHNAME', 'sparsevec_coo' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;++CREATE FUNCTION sparsevec(int[], numeric[], int) RETURNS sparsevec+ AS 'MODULE_PATHNAME', 'sparsevec_coo' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;+
-- sparsevec private functions
CREATE FUNCTION sparsevec_lt(sparsevec, sparsevec) RETURNS bool
diff --git a/src/sparsevec.c b/src/sparsevec.cindex d7811c75e..6d0387fe7 100644--- a/src/sparsevec.c+++ b/src/sparsevec.c@@ -807,6 +807,140 @@ array_to_sparsevec(PG_FUNCTION_ARGS)
PG_RETURN_POINTER(result);
}
+/*+ * Construct a sparse vector from parallel arrays of 1-based indices and values.+ *+ * This is the array-based equivalent of the text constructor: the call+ * sparsevec(ARRAY[1,3], ARRAY[0.1,0.5]::real[], 1000)+ * produces the same result as casting the literal '{1:0.1,3:0.5}/1000'.+ *+ * Indices are 1-based (SQL convention) and may be supplied in any order;+ * they are sorted internally. Zero values are silently discarded, matching+ * the behaviour of sparsevec_in() and array_to_sparsevec(). The third+ * argument is the total number of dimensions of the vector space, which+ * cannot be inferred from the index/value arrays alone.+ */+FUNCTION_PREFIX PG_FUNCTION_INFO_V1(sparsevec_coo);+Datum+sparsevec_coo(PG_FUNCTION_ARGS)+{+ ArrayType *indices_array = PG_GETARG_ARRAYTYPE_P(0);+ ArrayType *values_array = PG_GETARG_ARRAYTYPE_P(1);+ int32 dim = PG_GETARG_INT32(2);+ SparseVector *result;+ int16 typlen;+ bool typbyval;+ char typalign;+ Datum *idxelemp;+ Datum *valelemp;+ int nidx,+ nval;+ SparseInputElement *elements;+ int nnz = 0;+ float *rvalues;++ if (ARR_NDIM(indices_array) > 1)+ ereport(ERROR,+ (errcode(ERRCODE_DATA_EXCEPTION),+ errmsg("indices array must be 1-D")));++ if (ARR_NDIM(values_array) > 1)+ ereport(ERROR,+ (errcode(ERRCODE_DATA_EXCEPTION),+ errmsg("values array must be 1-D")));++ if (ARR_HASNULL(indices_array) && array_contains_nulls(indices_array))+ ereport(ERROR,+ (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),+ errmsg("indices array must not contain nulls")));++ if (ARR_HASNULL(values_array) && array_contains_nulls(values_array))+ ereport(ERROR,+ (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),+ errmsg("indices array must not contain nulls")));++ get_typlenbyvalalign(ARR_ELEMTYPE(indices_array), &typlen, &typbyval, &typalign);+ deconstruct_array(indices_array, ARR_ELEMTYPE(indices_array), typlen, typbyval, typalign, &idxelemp, NULL, &nidx);++ get_typlenbyvalalign(ARR_ELEMTYPE(values_array), &typlen, &typbyval, &typalign);+ deconstruct_array(values_array, ARR_ELEMTYPE(values_array), typlen, typbyval, typalign, &valelemp, NULL, &nval);++ if (nidx != nval)+ ereport(ERROR,+ (errcode(ERRCODE_DATA_EXCEPTION),+ errmsg("indices and values arrays must have the same length")));++ CheckDim(dim);+ CheckNnz(nidx, dim); /* nidx is an upper bound since zeros will be dropped */++ elements = palloc(nidx * sizeof(SparseInputElement));++ if (ARR_ELEMTYPE(values_array) != INT4OID &&+ ARR_ELEMTYPE(values_array) != FLOAT4OID &&+ ARR_ELEMTYPE(values_array) != FLOAT8OID &&+ ARR_ELEMTYPE(values_array) != NUMERICOID)+ ereport(ERROR,+ (errcode(ERRCODE_DATA_EXCEPTION),+ errmsg("unsupported array type")));++ for (int i = 0; i < nidx; i++)+ {+ int32 idx = DatumGetInt32(idxelemp[i]);+ float val;++ if (ARR_ELEMTYPE(values_array) == FLOAT4OID)+ val = DatumGetFloat4(valelemp[i]);+ else if (ARR_ELEMTYPE(values_array) == FLOAT8OID)+ val = (float) DatumGetFloat8(valelemp[i]);+ else if (ARR_ELEMTYPE(values_array) == INT4OID)+ val = (float) DatumGetInt32(valelemp[i]);+ else+ val = DatumGetFloat4(DirectFunctionCall1(numeric_float4, valelemp[i]));++ /* Validate before converting: indices are 1-based in SQL */+ if (idx < 1 || idx > dim)+ ereport(ERROR,+ (errcode(ERRCODE_DATA_EXCEPTION),+ errmsg("sparsevec index out of bounds")));++ CheckElement(val);++ /* Do not store zero values, consistent with sparsevec_in */+ if (val != 0)+ {+ /* Convert 1-based numbering (SQL) to 0-based (C) */+ elements[nnz].index = idx - 1;+ elements[nnz].value = val;+ nnz++;+ }+ }++ /*+ * Sort elements (idx and val) by index so the result satisfies the ascending-order invariant.+ */+ qsort(elements, nnz, sizeof(SparseInputElement), CompareIndices);++ result = InitSparseVector(dim, nnz);+ rvalues = SPARSEVEC_VALUES(result);++ for (int i = 0; i < nnz; i++)+ {+ result->indices[i] = elements[i].index;+ rvalues[i] = elements[i].value;+ /* Verifies bounds and strict ascending order (catches duplicates) */+ CheckIndex(result->indices, i, dim);+ }++ /*+ * Free allocations from deconstruct_array.+ */+ pfree(elements);+ pfree(idxelemp);+ pfree(valelemp);++ PG_RETURN_SPARSEVEC_P(result);+}+
/*
* Get the L2 squared distance between sparse vectors
*/
diff --git a/test/expected/sparsevec.out b/test/expected/sparsevec.outindex 989ec82bc..ce6b3d264 100644--- a/test/expected/sparsevec.out+++ b/test/expected/sparsevec.out@@ -651,3 +651,98 @@ SELECT l2_normalize('{2:3e37,4:3e-37,6:4e37,8:4e-37}/9'::sparsevec);
{2:0.6,6:0.8}/9
(1 row)
+-- sparsevec constructor from indices and values arrays+-- basic construction+SELECT sparsevec(ARRAY[1,3], ARRAY[1.5,3.5]::real[], 5);+ sparsevec +-----------------+ {1:1.5,3:3.5}/5+(1 row)++-- equivalent to text literal+SELECT sparsevec(ARRAY[1,3], ARRAY[1.5,3.5]::real[], 5) = '{1:1.5,3:3.5}/5'::sparsevec;+ ?column? +----------+ t+(1 row)++-- unsorted input is sorted automatically+SELECT sparsevec(ARRAY[3,1], ARRAY[3.5,1.5]::real[], 5);+ sparsevec +-----------------+ {1:1.5,3:3.5}/5+(1 row)++-- zero values are silently dropped+SELECT sparsevec(ARRAY[1,2,3], ARRAY[1.0,0.0,2.0]::real[], 5);+ sparsevec +-------------+ {1:1,3:2}/5+(1 row)++-- all zeros yields empty sparse vector+SELECT sparsevec(ARRAY[1,2,3], ARRAY[0.0,0.0,0.0]::real[], 3);+ sparsevec +-----------+ {}/3+(1 row)++-- index equal to dim (upper bound) is valid+SELECT sparsevec(ARRAY[5], ARRAY[1.0]::real[], 5);+ sparsevec +-----------+ {5:1}/5+(1 row)++-- error: array length mismatch+SELECT sparsevec(ARRAY[1,2], ARRAY[1.0]::real[], 5);+ERROR: indices and values arrays must have the same length+-- error: index 0 is out of bounds (1-based)+SELECT sparsevec(ARRAY[0], ARRAY[1.0]::real[], 5);+ERROR: sparsevec index out of bounds+-- error: index exceeds dim+SELECT sparsevec(ARRAY[6], ARRAY[1.0]::real[], 5);+ERROR: sparsevec index out of bounds+-- error: negative index+SELECT sparsevec(ARRAY[-1], ARRAY[1.0]::real[], 5);+ERROR: sparsevec index out of bounds+-- error: duplicate indices+SELECT sparsevec(ARRAY[1,1], ARRAY[1.0,2.0]::real[], 5);+ERROR: sparsevec indices must not contain duplicates+-- error: NaN not allowed+SELECT sparsevec(ARRAY[1], ARRAY['NaN']::real[], 5);+ERROR: NaN not allowed in sparsevec+-- error: infinite value not allowed+SELECT sparsevec(ARRAY[1], ARRAY['Infinity']::real[], 5);+ERROR: infinite value not allowed in sparsevec+-- error: dim must be at least 1+SELECT sparsevec(ARRAY[1], ARRAY[1.0]::real[], 0);+ERROR: sparsevec must have at least 1 dimension+-- error: dim exceeds maximum+SELECT sparsevec(ARRAY[1], ARRAY[1.0]::real[], 1000000001);+ERROR: sparsevec cannot have more than 1000000000 dimensions+-- error: 2-D arrays not accepted+SELECT sparsevec(ARRAY[[1,2]]::int[], ARRAY[1.0,2.0]::real[], 5);+ERROR: indices array must be 1-D+-- error: null elements not accepted+SELECT sparsevec(ARRAY[1, NULL]::int[], ARRAY[1.0,2.0]::real[], 5);+ERROR: indices array must not contain nulls+-- value array types+SELECT sparsevec(ARRAY[1,3], ARRAY[2,4]::integer[], 5);+ sparsevec +-------------+ {1:2,3:4}/5+(1 row)++SELECT sparsevec(ARRAY[1,3], ARRAY[1.5,3.5]::double precision[], 5);+ sparsevec +-----------------+ {1:1.5,3:3.5}/5+(1 row)++SELECT sparsevec(ARRAY[1,3], ARRAY[1.5,3.5]::numeric[], 5);+ sparsevec +-----------------+ {1:1.5,3:3.5}/5+(1 row)+diff --git a/test/sql/sparsevec.sql b/test/sql/sparsevec.sqlindex 2e1136b8d..5559e09d1 100644--- a/test/sql/sparsevec.sql+++ b/test/sql/sparsevec.sql@@ -132,3 +132,46 @@ SELECT l2_normalize('{}/2'::sparsevec);
SELECT l2_normalize('{1:3e38}/1'::sparsevec);
SELECT l2_normalize('{1:3e38,2:1e-37}/2'::sparsevec);
SELECT l2_normalize('{2:3e37,4:3e-37,6:4e37,8:4e-37}/9'::sparsevec);
++-- sparsevec constructor from indices and values arrays++-- basic construction+SELECT sparsevec(ARRAY[1,3], ARRAY[1.5,3.5]::real[], 5);+-- equivalent to text literal+SELECT sparsevec(ARRAY[1,3], ARRAY[1.5,3.5]::real[], 5) = '{1:1.5,3:3.5}/5'::sparsevec;+-- unsorted input is sorted automatically+SELECT sparsevec(ARRAY[3,1], ARRAY[3.5,1.5]::real[], 5);+-- zero values are silently dropped+SELECT sparsevec(ARRAY[1,2,3], ARRAY[1.0,0.0,2.0]::real[], 5);+-- all zeros yields empty sparse vector+SELECT sparsevec(ARRAY[1,2,3], ARRAY[0.0,0.0,0.0]::real[], 3);+-- index equal to dim (upper bound) is valid+SELECT sparsevec(ARRAY[5], ARRAY[1.0]::real[], 5);++-- error: array length mismatch+SELECT sparsevec(ARRAY[1,2], ARRAY[1.0]::real[], 5);+-- error: index 0 is out of bounds (1-based)+SELECT sparsevec(ARRAY[0], ARRAY[1.0]::real[], 5);+-- error: index exceeds dim+SELECT sparsevec(ARRAY[6], ARRAY[1.0]::real[], 5);+-- error: negative index+SELECT sparsevec(ARRAY[-1], ARRAY[1.0]::real[], 5);+-- error: duplicate indices+SELECT sparsevec(ARRAY[1,1], ARRAY[1.0,2.0]::real[], 5);+-- error: NaN not allowed+SELECT sparsevec(ARRAY[1], ARRAY['NaN']::real[], 5);+-- error: infinite value not allowed+SELECT sparsevec(ARRAY[1], ARRAY['Infinity']::real[], 5);+-- error: dim must be at least 1+SELECT sparsevec(ARRAY[1], ARRAY[1.0]::real[], 0);+-- error: dim exceeds maximum+SELECT sparsevec(ARRAY[1], ARRAY[1.0]::real[], 1000000001);+-- error: 2-D arrays not accepted+SELECT sparsevec(ARRAY[[1,2]]::int[], ARRAY[1.0,2.0]::real[], 5);+-- error: null elements not accepted+SELECT sparsevec(ARRAY[1, NULL]::int[], ARRAY[1.0,2.0]::real[], 5);++-- value array types+SELECT sparsevec(ARRAY[1,3], ARRAY[2,4]::integer[], 5);+SELECT sparsevec(ARRAY[1,3], ARRAY[1.5,3.5]::double precision[], 5);+SELECT sparsevec(ARRAY[1,3], ARRAY[1.5,3.5]::numeric[], 5);