我在 Cassandra 中有一个电影表(托管在 Astra DB 上),其中有一个单独的主键
movie_id
。有几列,但对于我的矢量搜索,我真的只关心 title
。 movie_vector
列上有一个存储附加索引 (SAI),该索引是使用以下 CQL 创建的:
CREATE CUSTOM INDEX ON movieapp.movies (movie_vector) USING 'StorageAttachedIndex';
当我根据为“星球大战”定义的向量执行 CQL 向量搜索时,我得到以下结果:
SELECT title FROM movies
ORDER BY movie_vector ANN OF [37, 4, 8, 13, 42.1497, 8.1, 6778]
LIMIT 6;
title | movie_vector
-------------------------+-------------------------------------
Star Wars | [37, 4, 8, 13, 42.1497, 8.1, 6778]
The Empire Strikes Back | [37, 4, 8, 13, 19.47096, 8.2, 5998]
Return of the Jedi | [37, 4, 8, 13, 14.58609, 7.9, 4763]
The Lion King | [49, 1, 3, 7, 21.60576, 8, 5520]
Pocahontas | [10, 1, 3, 4, 13.28007, 6.7, 1509]
Batman | [18, 5, 8, 0, 19.10673, 7, 2145]
(6 rows)
这些结果是如何排序的?有什么方法可以看出背后的逻辑吗?
给定上面显示的默认值和索引,从 CQL 向量搜索返回的结果按照向量相对于原始向量的余弦相似度进行排序。这可以通过使用 CQL
similarity_cosine
函数看出,该函数接受 Vector<float, n>
类型的列和向量本身。
对于上面的查询,它会像这样工作:
SELECT title,
similarity_cosine(movie_vector, [37, 4, 8, 13, 42.1497, 8.1, 6778]) AS similarity
FROM movies
ORDER BY movie_vector ANN OF [37, 4, 8, 13, 42.1497, 8.1, 6778]
LIMIT 6;
title | similarity | movie_vector
-------------------------+------------+-------------------------------------
Star Wars | 1 | [37, 4, 8, 13, 42.1497, 8.1, 6778]
The Empire Strikes Back | 0.999998 | [37, 4, 8, 13, 19.47096, 8.2, 5998]
Return of the Jedi | 0.999996 | [37, 4, 8, 13, 14.58609, 7.9, 4763]
The Lion King | 0.999995 | [49, 1, 3, 7, 21.60576, 8, 5520]
Pocahontas | 0.999995 | [10, 1, 3, 4, 13.28007, 6.7, 1509]
Batman | 0.999992 | [18, 5, 8, 0, 19.10673, 7, 2145]
(6 rows)
如上所示,电影“星球大战”的向量是 100% 匹配。这是有道理的,因为这是查询中使用的向量 (
[37, 4, 8, 13, 42.1497, 8.1, 6778]
)。
剩余的行按其
similarity_cosine
的结果排序,这是基于其 movie_vector
与原始向量的接近程度。与原始向量最接近的行位于结果集的顶部,而距离较远的向量显示在底部。
这有点冗长,但仍然是显示矢量搜索结果如何排序的有用方法。