IndexFlat原理比较简单,把add进来的原始向量,全部保存起来。
在检索时,query向量和索引中的所有的原始向量求距离
这种暴力批量的方式,性能非常差,效果是最好的。
void IndexFlat::add (idx_t n, const float *x) {
xb.insert(xb.end(), x, x + n * d);
ntotal += n; ///所有向量
}
void IndexFlat::reset() {
xb.clear();
ntotal = 0;
}
/*n:向量个数, x:向量值, k:返回个数, distances:返回值, labels:返回值*/
void IndexFlat::search (idx_t n, const float *x, idx_t k,
float *distances, idx_t *labels) const
{
// we see the distances and labels as heaps
if (metric_type == METRIC_INNER_PRODUCT) {
float_minheap_array_t res = {
size_t(n), size_t(k), labels, distances};
knn_inner_product (x, xb.data(), d, n, ntotal, &res); ///向量内积
} else if (metric_type == METRIC_L2) {
float_maxheap_array_t res = {
size_t(n), size_t(k), labels, distances};