Overview
在本指南中,您可以学习如何在 Java 驱动程序中使用 MongoDB Vector Search 功能。Aggregates 构建器类提供了 vectorSearch() 辅助方法,可用于创建 $vectorSearch 管道阶段。此管道阶段允许您对文档进行语义搜索。语义搜索可以查找与您提供的搜索词或短语在含义上相似但不完全相同的信息。
执行向量搜索
要使用此功能,您必须创建向量搜索索引并为向量嵌入创建索引。要了解如何以编程方式创建向量搜索索引,请参阅索引指南中的MongoDB Search 和 Vector Search 索引部分。如要了解有关向量嵌入的更多信息,请参阅 Atlas 文档中的如何为向量搜索的向量嵌入创建索引。
在向量嵌入上创建向量搜索索引后,您可以在管道阶段引用此索引,如下节所示。
向量搜索示例
以下示例展示了如何构建一个聚合管道,从而使用 vectorSearch() 和 project() 方法计算向量搜索分数:
// Create an instance of the BinaryVector class as the query vector BinaryVector queryVector = BinaryVector.floatVector( new float[]{0.0001f, 1.12345f, 2.23456f, 3.34567f, 4.45678f}); // Specify the index name for the vector embedding index String indexName = "mflix_movies_embedding_index"; // Specify the path of the field to search on FieldSearchPath fieldSearchPath = fieldPath("plot_embedding"); // Limit the number of matches to 1 int limit = 1; // Create a pre-filter to only search within a subset of documents VectorSearchOptions options = exactVectorSearchOptions() .filter(gte("year", 2016)); // Create the vectorSearch pipeline stage List<Bson> pipeline = asList( vectorSearch( fieldSearchPath, queryVector, indexName, limit, options), project( metaVectorSearchScore("vectorSearchScore")));
提示
查询向量类型
前面的示例创建了一个 BinaryVector实例提供服务查询向量,但您也可以创建 Double 实例的 List。 但是,我们建议您使用 BinaryVector 类型以提高存储效率。
以下示例展示了如何运行聚合并从上述聚合管道的结果中打印向量搜索分数:
Document found = collection.aggregate(pipeline).first(); double score = found.getDouble("vectorSearchScore").doubleValue(); System.out.println("vectorSearch score: " + score);
API 文档
要进一步了解本指南所提及的方法和类型,请参阅以下 API 文档: