VECTOR_SUM

The VECTOR_SUM() function adds all vectors in a column and returns a vector which is the sum of those vectors.

Syntax

VECTOR_SUM(vector_expression)

Arguments

  • vector_expression: An expression that evaluates to a vector. Vectors can be stored in SingleStore using the BLOB type (Binary String Types).

Return Type

Returns the type of the argument (the vector_expression).

Using VECTOR_SUM with Vectors as BLOBs

The following examples demonstrate use of VECTOR_SUM with the BLOB type.

Example 1 - Adding Two Vectors

Create a table with a column of type BLOB to store the vectors and insert data into that table. The second column in this table, with column name vec and type BLOB, will store the vectors.

CREATE TABLE vectors_b (id int, vec BLOB not null);
INSERT INTO vectors_b VALUES (1, JSON_ARRAY_PACK('[0.1, 0.8, 0.2, 0.555]'));
INSERT INTO vectors_b VALUES (2, JSON_ARRAY_PACK('[0.45, 0.55, 0.495, 0.5]'));

The following query sums the vectors in the vec column and uses JSON_ARRAY_UNPACK to see the results in JSON format.

SELECT JSON_ARRAY_UNPACK(VECTOR_SUM(vec)) AS vector_sum
FROM vectors_b;
+---------------------------------------------------+
| vector_sum                                        |
+---------------------------------------------------+
| [0.550000012,1.35000002,0.694999993,1.05500007]   |
+---------------------------------------------------+
1 row in set (0.01 sec)

The following query uses HEX to view the results in hexadecimal format.

SELECT HEX(VECTOR_SUM(vec)) AS vector_sum
FROM vectors_b;
+---------------------------------------------------+
| vector_sum                                        |
+---------------------------------------------------+
| CDCC0C3FCDCCAC3F85EB313F3E0A873F                  |
+---------------------------------------------------+

Formatting Binary Vector Data for BLOBs

When using the BLOB type for vector operations, vector data can be formatted using JSON_ARRAY_PACK. If your vector data is already in a packed binary format, you can load that data into the BLOBs. The data must be encoded as a BLOB containing packed numbers in little-endian byte order. Vectors stored as BLOBs can be of any length; however, the input blob length must be divisible by the size of the packed vector elements .

Last modified:

Was this article helpful?