pg.ddx.io pgvector/pgvector GitHub issues and pull requests
help / color / mirror / Atom feed[pgvector/pgvector] PR #944: Add jsonb_to_vector and jsonb_to_halfvec cast functions
5+ messages / 5 participants
[nested] [flat]
* [pgvector/pgvector] PR #944: Add jsonb_to_vector and jsonb_to_halfvec cast functions
@ 2026-01-05 03:20 "jkatz (@jkatz)" <noreply+jkatz@github.com>
0 siblings, 0 replies; 5+ messages in thread
From: jkatz (@jkatz) @ 2026-01-05 03:20 UTC (permalink / raw)
To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>
This commit adds the ability to cast JSONB arrays directly into vector and halfvec vector types, for example:
```sql
SELECT '[1,2,3]'::jsonb::vector(3);
SELECT '[1,2,3]'::jsonb::halfvec(3);
```
There are several TODOs if the overall idea of the patch is acceptable:
* Determine if the method should be applied to `sparsevec` (and possibly bit vectors, but maybe a separate discussion given `bit` is a core type).
* Update README and other docs with examples.
* For discussion: to go from `vector` to `jsonb`, one must cast to an array (`to_jsonb(vector::real[])`) otherwise the value is stored as a string. It may be helpful to have a `vector_to_jsonb` function similar to how PostgreSQL has `array_to_json`.
------
## Motivation
There are several vector data sources that come from JSON documents, whether the embeddings are contained in them or they're being transformed from other sources, such as from data lake files. Additionally, some cases prefer not to duplicate the vector data between the JSON file and a separate vector column, though are fine to use the vector as an expression in a HNSW/IVFFlat index. The [previous discussion](https://github.com/pgvector/pgvector/issues/380#issuecomment-1858844472) concluded that the cast from `jsonb::text::vector` would work, but for cases with bulk imports or transformations, this adds nontrivial overhead.
## Testing
The tests show how the `jsonb_to_vector` functions performs compared to `jsonb::text::vector` cast. This was executed as `k=10` exact-nearest neighbor queries on a dataset of 100,000 vectors that all fit into memory. Each test was run until 50 or 500 transactions was completed, and the average of these transactions taken. The times are in milliseconds.
I went through a few different variations of the tests including:
1. Baselining against a regular, non-casted K-NN query
1. Casting from JSONB to an array to a vector type. This was 10x slower overall than the other results, thus not printing.
1. Casting from JSONB to text to a vector type
1. Casting directly from JSONB to a vector type
The below show the results from the last two tests
**`jsonb::text::vector`**
```sql
SELECT id,
(embedding_jsonb::text::vector(1536)) <=>
(SELECT embedding_vector FROM data WHERE id = ?) as distance
FROM data
ORDER BY distance
LIMIT 10;
```
**`jsonb_to_vector`** (similar for `jsonb_to_halfvec`)
```sql
SELECT id,
(embedding_jsonb::vector(1536)) <=>
(SELECT embedding_vector FROM data WHERE id = ?) as distance
FROM data
ORDER BY distance
LIMIT 10;
```
### Results
Most tests showed a direct jsonb to vector cast had close to a 20% speedup over the `jsonb::text::vector` method.
#### vector
Dimension | `jsonb::text::vector` | `jsonb_to_vector` | % Speedup
-- | -- | -- | --
128 | 282.594 | 237.999 | 15.8%
768 | 2343.711 | 1881.062 | 19.7%
1536 (external) | 4566.775 | 3723.697 | 18.5%
1536 (plain) | 3139.608 | 2532.739 | 19.3%
#### halfvec
Dimension | jsonb::text::halfvec | jsonb_to_halfvec | % Speedup
-- | -- | -- | --
128 | 290.947 | 237.163 | 18.5%
768 | 1623.813 | 1295.505 | 20.2%
1536 (external) | 4591.033 | 3695.503 | 19.5%
1536 (plain) | 3139.492 | 2509.346 | 20.1%
inline patch 1: sql/vector.sql, src/halfvec.c, src/vector.c and 2 more (+213/-0 lines) download inline-1.patch
diff --git a/sql/vector.sql b/sql/vector.sql
index 7fc36712b..8bfddf743 100644
--- a/sql/vector.sql
+++ b/sql/vector.sql
@@ -146,6 +146,9 @@ CREATE FUNCTION array_to_vector(double precision[], integer, boolean) RETURNS ve
CREATE FUNCTION array_to_vector(numeric[], integer, boolean) RETURNS vector
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
+CREATE FUNCTION jsonb_to_vector(jsonb, integer, boolean) RETURNS vector
+ AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
+
CREATE FUNCTION vector_to_float4(vector, integer, boolean) RETURNS real[]
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
@@ -169,6 +172,9 @@ CREATE CAST (double precision[] AS vector)
CREATE CAST (numeric[] AS vector)
WITH FUNCTION array_to_vector(numeric[], integer, boolean) AS ASSIGNMENT;
+CREATE CAST (jsonb AS vector)
+ WITH FUNCTION jsonb_to_vector(jsonb, integer, boolean) AS ASSIGNMENT;
+
-- vector operators
CREATE OPERATOR <-> (
@@ -482,6 +488,9 @@ CREATE FUNCTION array_to_halfvec(double precision[], integer, boolean) RETURNS h
CREATE FUNCTION array_to_halfvec(numeric[], integer, boolean) RETURNS halfvec
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
+CREATE FUNCTION jsonb_to_halfvec(jsonb, integer, boolean) RETURNS halfvec
+ AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
+
CREATE FUNCTION halfvec_to_float4(halfvec, integer, boolean) RETURNS real[]
AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;
@@ -511,6 +520,9 @@ CREATE CAST (double precision[] AS halfvec)
CREATE CAST (numeric[] AS halfvec)
WITH FUNCTION array_to_halfvec(numeric[], integer, boolean) AS ASSIGNMENT;
+CREATE CAST (jsonb AS halfvec)
+ WITH FUNCTION jsonb_to_halfvec(jsonb, integer, boolean) AS ASSIGNMENT;
+
-- halfvec operators
CREATE OPERATOR <-> (
diff --git a/src/halfvec.c b/src/halfvec.c
index 6854c3d71..f7309f2b1 100644
--- a/src/halfvec.c
+++ b/src/halfvec.c
@@ -15,6 +15,7 @@
#include "utils/array.h"
#include "utils/float.h"
#include "utils/fmgrprotos.h"
+#include "utils/jsonb.h"
#include "utils/lsyscache.h"
#include "utils/varbit.h"
#include "vector.h"
@@ -497,6 +498,60 @@ array_to_halfvec(PG_FUNCTION_ARGS)
PG_RETURN_POINTER(result);
}
+/*
+ * Convert jsonb to half vector
+ */
+ FUNCTION_PREFIX PG_FUNCTION_INFO_V1(jsonb_to_halfvec);
+ Datum
+ jsonb_to_halfvec(PG_FUNCTION_ARGS)
+ {
+ Jsonb *jsonb = PG_GETARG_JSONB_P(0);
+ int32 typmod = PG_GETARG_INT32(1);
+ HalfVector *result;
+ JsonbIterator *it;
+ JsonbValue v;
+ JsonbIteratorToken r;
+ int dim;
+ int i = 0;
+
+ if (!JB_ROOT_IS_ARRAY(jsonb) || JB_ROOT_IS_SCALAR(jsonb))
+ ereport(ERROR,
+ (errcode(ERRCODE_DATA_EXCEPTION),
+ errmsg("jsonb value must be array")));
+
+
+ dim = JsonContainerSize(&jsonb->root);
+ CheckDim(dim);
+ CheckExpectedDim(typmod, dim);
+
+ result = InitHalfVector(dim);
+ it = JsonbIteratorInit(&jsonb->root);
+
+ while ((r = JsonbIteratorNext(&it, &v, true)) != WJB_DONE && i < dim)
+ {
+ if (r != WJB_ELEM)
+ continue;
+
+ switch (v.type) {
+ case jbvNumeric:
+ result->x[i] = Float4ToHalf(DatumGetFloat4(DirectFunctionCall1(numeric_float4, NumericGetDatum(v.val.numeric))));
+ CheckElement(result->x[i]);
+ i++;
+ break;
+ case jbvNull:
+ ereport(ERROR,
+ (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
+ errmsg("array must not contain nulls")));
+ default:
+ ereport(ERROR,
+ (errcode(ERRCODE_DATA_EXCEPTION),
+ errmsg("expected number")));
+ }
+ }
+
+ PG_RETURN_POINTER(result);
+ }
+
/*
* Convert half vector to float4[]
*/
diff --git a/src/vector.c b/src/vector.c
index 473683801..1553fd5a8 100644
--- a/src/vector.c
+++ b/src/vector.c
@@ -18,6 +18,7 @@
#include "utils/array.h"
#include "utils/float.h"
#include "utils/fmgrprotos.h"
+#include "utils/jsonb.h"
#include "utils/lsyscache.h"
#include "utils/varbit.h"
#include "vector.h"
@@ -500,6 +501,59 @@ array_to_vector(PG_FUNCTION_ARGS)
PG_RETURN_POINTER(result);
}
+/*
+ * Convert jsonb to vector
+ */
+FUNCTION_PREFIX PG_FUNCTION_INFO_V1(jsonb_to_vector);
+Datum
+jsonb_to_vector(PG_FUNCTION_ARGS)
+{
+ Jsonb *jsonb = PG_GETARG_JSONB_P(0);
+ int32 typmod = PG_GETARG_INT32(1);
+ Vector *result;
+ JsonbIterator *it;
+ JsonbValue v;
+ JsonbIteratorToken r;
+ int dim;
+ int i = 0;
+
+ if (!JB_ROOT_IS_ARRAY(jsonb) || JB_ROOT_IS_SCALAR(jsonb))
+ ereport(ERROR,
+ (errcode(ERRCODE_DATA_EXCEPTION),
+ errmsg("jsonb value must be array")));
+
+ dim = JsonContainerSize(&jsonb->root);
+ CheckDim(dim);
+ CheckExpectedDim(typmod, dim);
+
+ result = InitVector(dim);
+ it = JsonbIteratorInit(&jsonb->root);
+
+ while ((r = JsonbIteratorNext(&it, &v, true)) != WJB_DONE && i < dim)
+ {
+ if (r != WJB_ELEM)
+ continue;
+
+ switch (v.type) {
+ case jbvNumeric:
+ result->x[i] = DatumGetFloat4(DirectFunctionCall1(numeric_float4, NumericGetDatum(v.val.numeric)));
+ CheckElement(result->x[i]);
+ i++;
+ break;
+ case jbvNull:
+ ereport(ERROR,
+ (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
+ errmsg("array must not contain nulls")));
+ default:
+ ereport(ERROR,
+ (errcode(ERRCODE_DATA_EXCEPTION),
+ errmsg("expected number")));
+ }
+ }
+
+ PG_RETURN_POINTER(result);
+}
+
/*
* Convert vector to float4[]
*/
diff --git a/test/expected/cast.out b/test/expected/cast.out
index c180fe621..cc6e73612 100644
--- a/test/expected/cast.out
+++ b/test/expected/cast.out
@@ -268,6 +268,74 @@ SELECT array_agg(n)::vector FROM generate_series(1, 16001) n;
ERROR: vector cannot have more than 16000 dimensions
SELECT array_to_vector(array_agg(n), 16001, false) FROM generate_series(1, 16001) n;
ERROR: vector cannot have more than 16000 dimensions
+SELECT '[1,2,3]'::jsonb::vector;
+ vector
+---------
+ [1,2,3]
+(1 row)
+
+SELECT '[1.0,2.0,3.0]'::jsonb::vector;
+ vector
+---------
+ [1,2,3]
+(1 row)
+
+SELECT '[1,2,3]'::jsonb::vector(3);
+ vector
+---------
+ [1,2,3]
+(1 row)
+
+SELECT '[1,2,3]'::jsonb::vector(2);
+ERROR: expected 2 dimensions, not 3
+SELECT '[null]'::jsonb::vector;
+ERROR: array must not contain nulls
+SELECT '["a"]'::jsonb::vector;
+ERROR: expected number
+SELECT '[1,2,"a"]'::jsonb::vector;
+ERROR: expected number
+SELECT '[]'::jsonb::vector;
+ERROR: vector must have at least 1 dimension
+SELECT '{}'::jsonb::vector;
+ERROR: jsonb value must be array
+SELECT '1'::jsonb::vector;
+ERROR: jsonb value must be array
+SELECT '[[1,2]]'::jsonb::vector;
+ERROR: expected number
+SELECT '[1,2,3]'::jsonb::halfvec;
+ halfvec
+---------
+ [1,2,3]
+(1 row)
+
+SELECT '[1.0,2.0,3.0]'::jsonb::halfvec;
+ halfvec
+---------
+ [1,2,3]
+(1 row)
+
+SELECT '[1,2,3]'::jsonb::halfvec(3);
+ halfvec
+---------
+ [1,2,3]
+(1 row)
+
+SELECT '[1,2,3]'::jsonb::halfvec(2);
+ERROR: expected 2 dimensions, not 3
+SELECT '[null]'::jsonb::halfvec;
+ERROR: array must not contain nulls
+SELECT '["a"]'::jsonb::halfvec;
+ERROR: expected number
+SELECT '[1,2,"a"]'::jsonb::halfvec;
+ERROR: expected number
+SELECT '[]'::jsonb::halfvec;
+ERROR: halfvec must have at least 1 dimension
+SELECT '{}'::jsonb::halfvec;
+ERROR: jsonb value must be array
+SELECT '1'::jsonb::halfvec;
+ERROR: jsonb value must be array
+SELECT '[[1,2]]'::jsonb::halfvec;
+ERROR: expected number
-- ensure no error
SELECT ARRAY[1,2,3] = ARRAY[1,2,3];
?column?
diff --git a/test/sql/cast.sql b/test/sql/cast.sql
index fe8393119..b8a9cd2e5 100644
--- a/test/sql/cast.sql
+++ b/test/sql/cast.sql
@@ -77,5 +77,29 @@ SELECT '{{1}}'::real[]::sparsevec;
SELECT array_agg(n)::vector FROM generate_series(1, 16001) n;
SELECT array_to_vector(array_agg(n), 16001, false) FROM generate_series(1, 16001) n;
+SELECT '[1,2,3]'::jsonb::vector;
+SELECT '[1.0,2.0,3.0]'::jsonb::vector;
+SELECT '[1,2,3]'::jsonb::vector(3);
+SELECT '[1,2,3]'::jsonb::vector(2);
+SELECT '[null]'::jsonb::vector;
+SELECT '["a"]'::jsonb::vector;
+SELECT '[1,2,"a"]'::jsonb::vector;
+SELECT '[]'::jsonb::vector;
+SELECT '{}'::jsonb::vector;
+SELECT '1'::jsonb::vector;
+SELECT '[[1,2]]'::jsonb::vector;
+
+SELECT '[1,2,3]'::jsonb::halfvec;
+SELECT '[1.0,2.0,3.0]'::jsonb::halfvec;
+SELECT '[1,2,3]'::jsonb::halfvec(3);
+SELECT '[1,2,3]'::jsonb::halfvec(2);
+SELECT '[null]'::jsonb::halfvec;
+SELECT '["a"]'::jsonb::halfvec;
+SELECT '[1,2,"a"]'::jsonb::halfvec;
+SELECT '[]'::jsonb::halfvec;
+SELECT '{}'::jsonb::halfvec;
+SELECT '1'::jsonb::halfvec;
+SELECT '[[1,2]]'::jsonb::halfvec;
+
-- ensure no error
SELECT ARRAY[1,2,3] = ARRAY[1,2,3];
^ permalink raw [nested|flat] 5+ messages in thread
* Re: [pgvector/pgvector] PR #944: Add jsonb_to_vector and jsonb_to_halfvec cast functions
@ 2026-01-12 17:06 ` "ankane (@ankane)" <noreply+ankane@github.com>
3 siblings, 0 replies; 5+ messages in thread
From: ankane (@ankane) @ 2026-01-12 17:06 UTC (permalink / raw)
To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>
Thanks @jkatz. I'm hesitant about including a direct cast for this, since I don't think it's super common and the existing cast is fairly performant.
^ permalink raw [nested|flat] 5+ messages in thread
* Re: [pgvector/pgvector] PR #944: Add jsonb_to_vector and jsonb_to_halfvec cast functions
@ 2026-05-07 06:44 ` "jayeshds (@jayeshds)" <noreply+jayeshds@github.com>
3 siblings, 0 replies; 5+ messages in thread
From: jayeshds (@jayeshds) @ 2026-05-07 06:44 UTC (permalink / raw)
To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>
wqess
^ permalink raw [nested|flat] 5+ messages in thread
* Re: [pgvector/pgvector] PR #944 (changes requested): Add jsonb_to_vector and jsonb_to_halfvec cast functions
@ 2026-06-14 03:50 ` "sagitrs (@sagitrs)" <noreply+sagitrs@github.com>
3 siblings, 0 replies; 5+ messages in thread
From: sagitrs (@sagitrs) @ 2026-06-14 03:50 UTC (permalink / raw)
To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>
-
^ permalink raw [nested|flat] 5+ messages in thread
* Re: [pgvector/pgvector] PR #944 (approved): Add jsonb_to_vector and jsonb_to_halfvec cast functions
@ 2026-08-28 13:45 ` "helmize1978 (@helmize1978)" <noreply+helmize1978@github.com>
3 siblings, 0 replies; 5+ messages in thread
From: helmize1978 (@helmize1978) @ 2026-08-28 13:45 UTC (permalink / raw)
To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>
^ permalink raw [nested|flat] 5+ messages in thread
end of thread, other threads:[~2026-08-28 13:45 UTC | newest]
Thread overview: 5+ messages (download: mbox mbox.gz follow: Atom feed)
-- links below jump to the message on this page --
2026-01-05 03:20 [pgvector/pgvector] PR #944: Add jsonb_to_vector and jsonb_to_halfvec cast functions "jkatz (@jkatz)" <noreply+jkatz@github.com>
2026-01-12 17:06 ` "ankane (@ankane)" <noreply+ankane@github.com>
2026-05-07 06:44 ` "jayeshds (@jayeshds)" <noreply+jayeshds@github.com>
2026-06-14 03:50 ` Re: [pgvector/pgvector] PR #944 (changes requested): Add jsonb_to_vector and jsonb_to_halfvec cast functions "sagitrs (@sagitrs)" <noreply+sagitrs@github.com>
2026-08-28 13:45 ` Re: [pgvector/pgvector] PR #944 (approved): Add jsonb_to_vector and jsonb_to_halfvec cast functions "helmize1978 (@helmize1978)" <noreply+helmize1978@github.com>
This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox