The COSINE_DISTANCE function calculates the cosine distance between two vectors.
Cosine similarity is based on the angle between two vectors in a multi-dimensional space, regardless of their magnitude. It is calculated by dividing the inner product of the two vectors by the product of their lengths. The cosine similarity is always in the interval [-1, 1]. For example, two identical vectors have a cosine similarity of 1, two orthogonal vectors have a cosine similarity of 0, and two vectors pointing in opposite directions have a cosine similarity of -1.
Syntax
FLOAT COSINE_DISTANCE( <vector>, <vector> )Parameters
vector: Required. A vector of the VECTOR data type.
Return value
Returns the cosine distance between the two input vectors as a FLOAT value in the range [0, 2].
Vector function optimization can cause a slight loss of floating-point precision. The result has a maximum error margin of 1e-4.
Examples
-- Enable the VECTOR data type.
set odps.sql.type.vector.enable=true;
set odps.sql.type.system.odps2=true;
-- Prepare data.
CREATE TABLE vectors (a VECTOR(FLOAT, 3), b VECTOR(FLOAT, 3));
INSERT INTO vectors SELECT CAST(ARRAY(1.1,2.2,3.0) AS VECTOR(FLOAT,3)), CAST(ARRAY(1.0,1.0,1.0) AS VECTOR(FLOAT,3));
INSERT INTO vectors SELECT CAST(ARRAY(1.0,2.2,3.0) AS VECTOR(FLOAT,3)), CAST(ARRAY(4.0,6.0,8.0) AS VECTOR(FLOAT,3));
SELECT a, COSINE_DISTANCE(a, CAST(ARRAY(1.0,2.0,3.0) AS VECTOR(FLOAT, 3))) AS similarity
FROM vectors
ORDER BY similarity DESC
LIMIT 1;
-- Result:
+------+------------+
| a | similarity |
+------+------------+
| [1.1, 2.2, 3] | 0.0010684728622436523 |
+------+------------+