相似性搜索
通常使用距离来描述向量间的相似度。当前向量数据库提供欧式距离、余弦距离以及汉明距离三种距离计算方式。其中影响欧式距离的包括向量间的角度差和长度差两方面;余弦距离则只关注向量间的角度差别;汉明距离仅用来计算boolvector,计算向量中不同元素的数量。
欧式距离相似性搜索示例
计算向量间欧氏距离时,仅支持floatvector类型向量使用:操作符<->和系统函数l2_distance。
- l2_distance操作符(<->)
gaussdb=# CREATE TABLE t1(id int unique, repr floatvector(4)); gaussdb=# INSERT INTO t1 VALUES(0, '[30,12,12,25]'); gaussdb=# SELECT id, repr<-> '[1,1,3,2]' AS s FROM t1; gaussdb=# SELECT floatvector('[1,2,3]')<->floatvector('[5,-1,3.5]');
- 系统函数(l2_distance)
gaussdb=# SELECT id, l2_distance(repr, '[1,1,3,2]') AS s FROM t1; gaussdb=# SELECT l2_distance(floatvector('[1,2,3]'), floatvector('[5,-1,3.5]'));
不定义的字符类型(unknown)可进行隐式转换
gaussdb=# SELECT l2_distance('[1,2,3]', '[5,-1,3.5]');
- 相同维度的数据字段进行相似性查找,输出结果: 支持多表关联场景
gaussdb=# CREATE TABLE t2(id int unique, repr floatvector(4)); gaussdb=# INSERT INTO t2 VALUES(0, '[30,12,12,25]'); gaussdb=# SELECT t1.repr FROM t1 inner JOIN t2 ON t1.repr <-> t2.repr < 0.8;
支持子查询场景gaussdb=# SELECT t1.id FROM t1 WHERE t1.repr <-> (SELECT t2.repr FROM t2 LIMIT 1) < 0.8;
余弦距离相似性搜索示例
计算向量间余弦距离时,仅支持 floatvector 类型向量使用:操作符<+>和系统函数cosine_distance。
- 操作符(<+>)
gaussdb=# select id, repr<+> '[1,1,3,2]' as s from t1; gaussdb=# select floatvector('[1,2,3]')<+>floatvector('[5,-1,3.5]');
- 系统函数(cosine_distance)
gaussdb=# select id, cosine_distance(repr, '[1,1,3,2]') as s from t1; gaussdb=# select cosine_distance(floatvector('[1,2,3]'), floatvector('[5,-1,3.5]'));
不定义的字符类型(unknown)可进行隐式转换
gaussdb=# select cosine_distance('[1,2,3]', '[5,-1,3.5]');
汉明距离相似性搜索示例
计算向量间汉明距离时,仅支持boolvector类型向量使用:操作符<#>和系统函数hamming_bool_distance。
- 操作符(<#>)
gaussdb=# DROP TABLE t2; gaussdb=# CREATE TABLE t2(id int unique, repr boolvector(3)); gaussdb=# INSERT INTO t2 VALUES(1, '[1, 0, 1]'); gaussdb=# select id, repr<#> '[1,1,0]' as s from t2; gaussdb=# select boolvector('[T,F,F]')<#>boolvector('[T,F,T]');
- 系统函数(hamming_bool_distance)
gaussdb=# select id, hamming_bool_distance(repr, '[1,1,0]') as s from t2; gaussdb=# select hamming_bool_distance(boolvector('[T,F,F]'), boolvector('[T,F,T]'));
不定义的字符类型(unknown)可进行隐式转换
gaussdb=# select hamming_bool_distance('[T,F,F]', '[T,F,T]');
- 同维度的数据字段进行相似性查找,输出结果:
gaussdb=# select id from t2 order by repr<#> '[1,1,0]' limit 2;支持多表关联场景
gaussdb=# CREATE TABLE t4(id int unique, repr boolvector(3)); gaussdb=# INSERT INTO t4 VALUES(1, '[1, 0, 1]'); gaussdb=# select t2.repr from t2 inner join t4 on t2.repr <#> t4.repr < 3;
支持子查询场景
gaussdb=# select t2.id from t2 where t2.repr <#> (select t4.repr from t4 limit 1) < 3;