使用向量嵌入搜索(续1)

指定距离阈值

您可以指定相似度阈值,以便仅返回相似度在阈值范围内的文档。阈值字段的行为取决于您选择的距离衡量方式:

  • EUCLIDEAN 和 COSINE 距离会将阈值限制为距离小于或等于指定阈值的文档。随着向量的相似度增加,这些距离衡量值会减小。
  • DOT_PRODUCT 距离会将阈值限制为距离大于或等于指定阈值的文档。随着向量的相似度增加,点积距离会增加。

以下示例展示了如何指定距离阈值,以使用 EUCLIDEAN 距离指标返回最多 10 个距离不超过 4.5 个单位的最近文档:

Python
from google.cloud.firestore_v1.base_vector_query import DistanceMeasure
from google.cloud.firestore_v1.vector import Vector

collection = db.collection("coffee-beans")

vector_query = collection.find_nearest(
    vector_field="embedding_field",
    query_vector=Vector([0.3416704, 0.18332680, 0.24160706]),
    distance_measure=DistanceMeasure.EUCLIDEAN,
    limit=10,
    distance_threshold=4.5,
)

docs = vector_query.stream()

for doc in docs:
    print(f"{doc.id}")

vector_search.py
Node.js
const vectorQuery: VectorQuery = coll.findNearest({
  vectorField: 'embedding_field',
  queryVector: [3.0, 1.0, 2.0],
  limit: 10,
  distanceMeasure: 'EUCLIDEAN',
  distanceThreshold: 4.5
});

const snapshot: VectorQuerySnapshot = await vectorQuery.get();

snapshot.forEach((doc) => {
  console.log(doc.id);
});
Go
import (
    "context"
    "fmt"
    "io"

    "cloud.google.com/go/firestore"
)

func vectorSearchDistanceThreshold(w io.Writer, projectID string) error {
    ctx := context.Background()

    client, err := firestore.NewClient(ctx, projectID)
    if err != nil {
        return fmt.Errorf("firestore.NewClient: %w", err)
    }
    defer client.Close()

    collection := client.Collection("coffee-beans")

    // Requires a vector index
    // https://firebase.google.com/docs/firestore/vector-search#create_and_manage_vector_indexes
    vectorQuery := collection.FindNearest("embedding_field",
        []float32{3.0, 1.0, 2.0},
        10,
        firestore.DistanceMeasureEuclidean,
        &firestore.FindNearestOptions{
            DistanceThreshold: firestore.Ptr[float64](4.5),
        })

    docs, err := vectorQuery.Documents(ctx).GetAll()
    if err != nil {
        fmt.Fprintf(w, "failed to get vector query results: %v", err)
        return err
    }

    for _, doc := range docs {
        fmt.Fprintln(w, doc.Data()["name"])
    }
    return nil
}

vector_search_distance_threshold.go
Java
import com.google.cloud.firestore.VectorQuery;
import com.google.cloud.firestore.VectorQueryOptions;
import com.google.cloud.firestore.VectorQuerySnapshot;

VectorQuery vectorQuery = coll.findNearest(
        "embedding_field",
        new double[] {3.0, 1.0, 2.0},
        /* limit */ 10,
        VectorQuery.DistanceMeasure.EUCLIDEAN,
        VectorQueryOptions.newBuilder()
          .setDistanceThreshold(4.5)
          .build());

ApiFuture<VectorQuerySnapshot> future = vectorQuery.get();
VectorQuerySnapshot vectorQuerySnapshot = future.get();

for (DocumentSnapshot document : vectorQuerySnapshot.getDocuments()) {
    System.out.println(document.getId());
}

限制

请注意,在使用向量嵌入时,有以下限制:

  • 支持的嵌入维度上限为 2,048。如要存储更大的索引,可使用降维。
  • 通过最近邻查询返回的文档数量上限为 1,000。
  • 向量搜索不支持实时快照监听器。
  • 只有 Python、Node.js、Go 和 Java 客户端库支持向量搜索。

后续步骤