id: search.md related_key: search

summary: Conduct a vector similarity search with Milvus.

向量相似性搜索

本主题介绍如何使用 Milvus 搜索 entities 。

Milvus 中的向量相似度搜索计算查询向量与 collection 中具有指定相似度度量的向量之间的距离,并返回最相似的结果。通过指定过滤标量 field 或者 primary key field 的 布尔表达式 ,你可以执行 混合搜索,甚至使用 Time Travel 来进行搜索。

下面的例子展示了如何对一个拥有 2000 行数据的数据集进行向量相似度搜索,模拟你基于书籍介绍的特征向量搜索某些书籍的情况。该数据集包含 book ID (primary key) 、 word count (scalar field) 和 book introduction (vector field)。 Milvus 会根据你定义的查询向量和搜索参数返回最相似的结果。

加载 collection

Milvus 中的所有搜索和结构化匹配操作都在内存中执行。在执行向量相似性搜索之前将 collection 加载到内存中。

{{fragments/multiple_code.md}}

  1. from pymilvus import Collection
  2. collection = Collection("book") # Get an existing collection.
  3. collection.load()
  1. await milvusClient.collectionManager.loadCollection({
  2. collection_name: "book",
  3. });
  1. err := milvusClient.LoadCollection(
  2. context.Background(), // ctx
  3. "book", // CollectionName
  4. false // async
  5. )
  6. if err != nil {
  7. log.Fatal("failed to load collection:", err.Error())
  8. }
  1. milvusClient.loadCollection(
  2. LoadCollectionParam.newBuilder()
  3. .withCollectionName("book")
  4. .build());
  1. load -c book

准备搜索参数

准备适合你的搜索场景的参数。下面的示例定义了搜索将使用欧式距离计算,并从 IVF_FLAT 索引构建的十个最近的聚类中检索向量。

{{fragments/multiple_code.md}}

  1. search_params = {"metric_type": "L2", "params": {"nprobe": 10}}
  1. const searchParams = {
  2. anns_field: "book_intro",
  3. topk: "2",
  4. metric_type: "L2",
  5. params: JSON.stringify({ nprobe: 10 }),
  6. };
  1. sp, _ := entity.NewIndexFlatSearchParam( // NewIndex*SearchParam func
  2. 10, // searchParam
  3. )
  1. final Integer SEARCH_K = 2; // TopK
  2. final String SEARCH_PARAM = "{\"nprobe\":10}"; // Params
  1. search
  2. Collection name (book): book
  3. The vectors of search data(the length of data is number of query (nq), the dim of every vector in data must be equal to vector fields of collection. You can also import a csv file without headers): [[0.1, 0.2]]
  4. The vector field used to search of collection (book_intro): book_intro
  5. Metric type: L2
  6. Search parameter nprobe's value: 10
  7. The max number of returned record, also known as topk: 10
  8. The boolean expression used to filter attribute []:
  9. The names of partitions to search (split by "," if multiple) ['_default'] []:
  10. timeout []:
  11. Guarantee Timestamp(It instructs Milvus to see all operations performed before a provided timestamp. If no such timestamp is provided, then Milvus will search all operations performed to date) [0]:
  12. Travel Timestamp(Specify a timestamp in a search to get results based on a data view) [0]:
参数 说明
metric_type 用于衡量向量相似性的指标。详细信息请参考 距离计算方式
params 该索引特有的搜索参数。详细信息请参考 向量索引
参数 说明
anns_field 要搜索的 field 名称。
topk 输出向量结果数。
metric_type 用于衡量向量相似性的指标。详细信息请参考 距离计算方式
params 该索引特有的搜索参数。详细信息请参考 向量索引
参数 说明 选项
NewIndex*SearchParam func 根据不同的索引类型创建 entity.SearchParam 的函数。 浮点型向量:
  • NewIndexFlatSearchParam (FLAT)
  • NewIndexIvfFlatSearchParam (IVF_FLAT)
  • NewIndexIvfSQ8SearchParam (IVF_SQ8)
  • NewIndexIvfPQSearchParam (RNSG)
  • NewIndexRNSGSearchParam (HNSW)
  • NewIndexHNSWSearchParam (HNSW)
  • NewIndexANNOYSearchParam (ANNOY)
  • NewIndexRHNSWFlatSearchParam (RHNSW_FLAT)
  • NewIndexRHNSW_PQSearchParam (RHNSW_PQ)
  • NewIndexRHNSW_SQSearchParam (RHNSW_SQ)
二进制型向量:
  • NewIndexBinFlatSearchParam (BIN_FLAT)
  • NewIndexBinIvfFlatSearchParam (BIN_IVF_FLAT)
searchParam 该索引特有的搜索参数。 详细信息请参考 向量索引
参数 说明 选项
TopK 输出向量结果数。 N/A
Params 该索引特有的搜索参数。 详细信息请参考 向量索引
选项 全称 说明
—help n/a 显示使用命令的帮助。

进行向量搜索

使用 Milvus 搜索向量。要在特定的partition中搜索,请指定 partition 名称列表。

Milvus 支持专门为搜索或结构化匹配设置一致性级别(目前仅在 PyMilvus 上)。在创建 collection 时,搜索或结构化匹配请求中设置的一致性级别将覆盖设置的一致性级别。在本例中,搜索请求的一致性级别设置为 “Strong”,这意味着 Milvus 将在搜索或结构化匹配请求出现的确切时间点读取最新的数据视图。如果在搜索或结构化匹配期间不指定一致性级别,Milvus 将采用创建 collection 的原始一致性级别。

{{fragments/multiple_code.md}}

  1. results = collection.search(
  2. data=[[0.1, 0.2]],
  3. anns_field="book_intro",
  4. param=search_params,
  5. limit=10,
  6. expr=None,
  7. consistency_level="Strong"
  8. )
  1. const results = await milvusClient.dataManager.search({
  2. collection_name: "book",
  3. expr: "",
  4. vectors: [[0.1, 0.2]],
  5. search_params: searchParams,
  6. vector_type: 101, // DataType.FloatVector
  7. });
  1. searchResult, err := milvusClient.Search(
  2. context.Background(), // ctx
  3. "book", // CollectionName
  4. []string{}, // partitionNames
  5. "", // expr
  6. []string{"book_id"}, // outputFields
  7. []entity.Vector{entity.FloatVector([]float32{0.1, 0.2})}, // vectors
  8. "book_intro", // vectorField
  9. entity.L2, // metricType
  10. 2, // topK
  11. sp, // sp
  12. )
  13. if err != nil {
  14. log.Fatal("fail to search collection:", err.Error())
  15. }
  1. List<String> search_output_fields = Arrays.asList("book_id");
  2. List<List<Float>> search_vectors = Arrays.asList(Arrays.asList(0.1f, 0.2f));
  3. SearchParam searchParam = SearchParam.newBuilder()
  4. .withCollectionName("book")
  5. .withMetricType(MetricType.L2)
  6. .withOutFields(search_output_fields)
  7. .withTopK(SEARCH_K)
  8. .withVectors(search_vectors)
  9. .withVectorFieldName("book_intro")
  10. .withParams(SEARCH_PARAM)
  11. .build();
  12. R<SearchResults> respSearch = milvusClient.search(searchParam);
  1. # Follow the previous step.
参数 说明
data 用于搜索的向量。
anns_field 要搜索的 field 名称。
params 该索引特有的搜索参数。详细信息请参考 向量索引
limit 输出向量结果数。
expr 用于过滤属性的布尔表达式。有关详细信息,请参考 布尔表达式规则
partition_names (optional) 要搜索的 partition 名称列表
output_fields (optional) 返回的 field 名称。当前版本不支持 Vector filed 。
timeout (optional) 允许 RPC 的持续时间(以秒为单位)。当设置为 None 时,客户端等待服务器响应或者发生错误。
round_decimal (optional) 返回距离的小数位数。
consistency_level (optional) 搜索的一致性级别。
参数 说明
collection_name 要搜索的 collection 名称。
search_params 用于搜索的参数(作为对象)。
vectors 用于搜索的向量。
vector_type 二进制型或浮点型向量的预检查。二进制型向量为100 ,浮点型向量为101
partition_names (optional) 要搜索的 partition 名称列表。
expr (optional) 用于过滤属性的布尔表达式。有关详细信息,请参考 布尔表达式规则
output_fields (optional) 返回的 field 名称。当前版本不支持 Vector field 。
参数 说明 选项
ctx 控制调用 API 的 Context。 N/A
CollectionName 要加载的 collection 名称。 N/A
partitionNames 要加载的 partition 名称列表。如果将其置空,将搜索所有的 partition 。 N/A
expr Boolean expression used to filter attribute. 有关详细信息,请参考 布尔表达式规则
output_fields 要返回的 field 名称。 当前版本不支持 vector field 。
vectors 用于搜索的向量。 N/A
vectorField 要搜索的 filed 名称。 N/A
metricType 用于搜索的指标类型。 此参数必须设置为与用于索引构建的指标类型相同。
topK 输出向量结果数。 N/A
sp 该索引特有的搜索参数 entity.SearchParam 。 N/A
参数 说明 选项
CollectionName 要加载的 collection 名称。 N/A
MetricType 距离计算方式 此参数必须设置为与用于索引构建的指标类型相同。
OutFields 要返回的 field 名称。. 当前版本不支持 vector field 。
Vectors 用于搜索的向量。 N/A
VectorFieldName 要搜索的 field 名称。 N/A
Expr 用于过滤属性的布尔表达式。 有关详细信息,请参考 布尔表达式规则

查看最相似向量的 primary key 及其距离值。

{{fragments/multiple_code.md}}

  1. results[0].ids
  2. results[0].distances
  1. console.log(results.results)
  1. fmt.Printf("%#v\n", searchResult)
  2. for _, sr := range searchResult {
  3. fmt.Println(sr.IDs)
  4. fmt.Println(sr.Scores)
  5. }
  1. SearchResultsWrapper wrapperSearch = new SearchResultsWrapper(respSearch.getData().getResults());
  2. System.out.println(wrapperSearch.getIDScore(0));
  3. System.out.println(wrapperSearch.getFieldData("book_id", 0));
  1. # Milvus CLI automatically returns the primary key values of the most similar vectors and their distances.

搜索完成时释放 Milvus 中加载的 collection 以减少内存消耗。

{{fragments/multiple_code.md}}

  1. collection.release()
  1. await milvusClient.collectionManager.releaseCollection({ collection_name: "book",});
  1. err := milvusClient.ReleaseCollection(
  2. context.Background(), // ctx
  3. "book", // CollectionName
  4. )
  5. if err != nil {
  6. log.Fatal("failed to release collection:", err.Error())
  7. }
  1. milvusClient.releaseCollection(
  2. ReleaseCollectionParam.newBuilder()
  3. .withCollectionName("book")
  4. .build());
  1. release -c book

限制

特性 最大限制
collection 的名称长度 255 characters
collection 中的 partition 数量 4,096
collection 中的 field 数量 256
collection 中的 shard 数 256
向量维度 32,768
Top K 16,384
目标输入向量数 16,384

更多内容