空间
在向量搜索中,*空间*定义了如何计算两个向量之间的距离(或相似性)。空间的选择会影响在搜索操作期间如何确定最近邻居。
距离计算
空间定义了用于测量两点之间距离的函数,以确定 k 最近邻。在 k-NN 搜索中,较低的分数表示更近、更好的结果。这与 OpenSearch 评分结果的方式相反,OpenSearch 中较高的分数表示更好的结果。OpenSearch 支持以下空间:
并非所有方法/引擎组合都支持每种空间。有关支持空间的列表,请参阅方法文档中特定引擎的部分。
空间类型 | 搜索类型 | 距离函数 (\(d\) ) | OpenSearch 分数 |
---|---|---|---|
l1 | 近似,精确 | \(d(\mathbf{x}, \mathbf{y}) = \sum_{i=1}^n \lvert x_i - y_i \rvert\) | \(score = {1 \over {1 + d} }\) |
l2 | 近似,精确 | \(d(\mathbf{x}, \mathbf{y}) = \sum_{i=1}^n (x_i - y_i)^2\) | \(score = {1 \over 1 + d }\) |
linf | 近似,精确 | \(d(\mathbf{x}, \mathbf{y}) = max(\lvert x_i - y_i \rvert)\) | \(score = {1 \over 1 + d }\) |
cosinesimil | 近似,精确 | \(d(\mathbf{x}, \mathbf{y}) = 1 - cos { \theta } = 1 - {\mathbf{x} \cdot \mathbf{y} \over \lVert \mathbf{x}\rVert \cdot \lVert \mathbf{y}\rVert}\)\(= 1 - {\sum_{i=1}^n x_i y_i \over \sqrt{\sum_{i=1}^n x_i^2} \cdot \sqrt{\sum_{i=1}^n y_i^2}}\), 其中 \(\lVert \mathbf{x}\rVert\) 和 \(\lVert \mathbf{y}\rVert\) 分别表示向量 \(\mathbf{x}\) 和 \(\mathbf{y}\) 的范数。 | \(score = {2 - d \over 2}\) |
innerproduct (OpenSearch 2.13 及更高版本中的 Lucene 支持) | 近似 | NMSLIB 和 Faiss \(d(\mathbf{x}, \mathbf{y}) = - {\mathbf{x} \cdot \mathbf{y}} = - \sum_{i=1}^n x_i y_i\) Lucene: \(d(\mathbf{x}, \mathbf{y}) = {\mathbf{x} \cdot \mathbf{y}} = \sum_{i=1}^n x_i y_i\) | NMSLIB 和 Faiss \(\text{If} d \ge 0, score = {1 \over 1 + d }\) \(\text{If} d < 0, score = −d + 1\) Lucene \(\text{If} d > 0, score = d + 1\) \(\text{If} d \le 0, score = {1 \over 1 + (-1 \cdot d) }\) |
innerproduct (OpenSearch 2.13 及更高版本中的 Lucene 支持) | 精确 | \(d(\mathbf{x}, \mathbf{y}) = - {\mathbf{x} \cdot \mathbf{y}} = - \sum_{i=1}^n x_i y_i\) | \(\text{If} d \ge 0, score = {1 \over 1 + d }\) \(\text{If} d < 0, score = −d + 1\) |
hamming (OpenSearch 2.16 及更高版本中支持二进制向量) | 近似,精确 | \(d(\mathbf{x}, \mathbf{y}) = \text{countSetBits}(\mathbf{x} \oplus \mathbf{y})\) | \(score = {1 \over 1 + d }\) |
hammingbit (支持二进制和长向量) | 精确 | \(d(\mathbf{x}, \mathbf{y}) = \text{countSetBits}(\mathbf{x} \oplus \mathbf{y})\) | \(score = {1 \over 1 + d }\) |
余弦相似度公式不包含 1 -
前缀。然而,由于相似度搜索库将较低的分数等同于更接近的结果,它们在余弦相似度空间中返回 1 - cosineSimilarity
——这就是为什么距离函数中包含 1 -
的原因。
对于余弦相似度,传入零向量([0, 0, ...]
)作为输入是无效的。这是因为此类向量的模为 0,这会在相应的公式中引发 除以 0
异常。包含零向量的请求将被拒绝,并抛出相应的异常。
OpenSearch 2.16 及更高版本支持二进制向量的 hamming
空间类型。有关更多信息,请参阅二进制 k-NN 向量。
指定空间类型
在创建索引时指定空间类型。
您可以在字段映射的顶层指定空间类型
PUT /test-index
{
"settings": {
"index": {
"knn": true
}
},
"mappings": {
"properties": {
"my_vector1": {
"type": "knn_vector",
"dimension": 3,
"space_type": "l2"
}
}
}
}
或者,如果定义方法,您可以在 method
对象中指定空间类型
PUT test-index
{
"settings": {
"index": {
"knn": true,
"knn.algo_param.ef_search": 100
}
},
"mappings": {
"properties": {
"my_vector1": {
"type": "knn_vector",
"dimension": 1024,
"method": {
"name": "hnsw",
"space_type": "l2",
"engine": "nmslib",
"parameters": {
"ef_construction": 128,
"m": 24
}
}
}
}
}
}