id: hybridsearch.md related_key: filter

summary: Conduct a Hybrid Search with Milvus.

混合搜索

当前主题介绍如何进行混合搜索。

混合搜索本质上是带有属性过滤的向量搜索。通过指定过滤标量 field 或者主键 field 的 布尔表达式,你可以使用特定条件限制搜索。

下面的例子展示了如何在 向量搜索 的基础上进行混合搜索。假设你想基于书籍介绍的特征向量搜索某些书籍,然而你只需要特定 word count 范围内的书籍。你可以指定布尔表达式来过滤过滤搜索参数中的 word_count field。Milvus 只会在匹配表达式的 entity 中搜索相似的向量。

加载 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

混合向量搜索

通过指定布尔表达式,你可以在向量搜索过程中过滤 entity 的标量 field。以下示例将搜索范围限制为指定 word_count 值范围内的向量。

{{fragments/multiple_code.md}}

  1. search_param = {
  2. "data": [[0.1, 0.2]],
  3. "anns_field": "book_intro",
  4. "param": {"metric_type": "L2", "params": {"nprobe": 10}},
  5. "limit": 2,
  6. "expr": "word_count <= 11000",
  7. }
  8. res = collection.search(**search_param)
  1. const results = await milvusClient.dataManager.search({
  2. collection_name: "book",
  3. expr: "word_count <= 11000",
  4. vectors: [[0.1, 0.2]],
  5. search_params: {
  6. anns_field: "book_intro",
  7. topk: "2",
  8. metric_type: "L2",
  9. params: JSON.stringify({ nprobe: 10 }),
  10. },
  11. vector_type: 101, // DataType.FloatVector,
  12. });
  1. sp, _ := entity.NewIndexFlatSearchParam( // NewIndex*SearchParam func
  2. 10, // searchParam
  3. )
  4. searchResult, err := milvusClient.Search(
  5. context.Background(), // ctx
  6. "book", // CollectionName
  7. []string{}, // partitionNames
  8. "word_count <= 11000", // expr
  9. []string{"book_id"}, // outputFields
  10. []entity.Vector{entity.FloatVector([]float32{0.1, 0.2})}, // vectors
  11. "book_intro", // vectorField
  12. entity.L2, // metricType
  13. 2, // topK
  14. sp, // sp
  15. )
  16. if err != nil {
  17. log.Fatal("fail to search collection:", err.Error())
  18. }
  1. final Integer SEARCH_K = 2;
  2. final String SEARCH_PARAM = "{\"nprobe\":10}";
  3. List<String> search_output_fields = Arrays.asList("book_id");
  4. List<List<Float>> search_vectors = Arrays.asList(Arrays.asList(0.1f, 0.2f));
  5. SearchParam searchParam = SearchParam.newBuilder()
  6. .withCollectionName("book")
  7. .withMetricType(MetricType.L2)
  8. .withOutFields(search_output_fields)
  9. .withTopK(SEARCH_K)
  10. .withVectors(search_vectors)
  11. .withVectorFieldName("book_intro")
  12. .withExpr("word_count <= 11000")
  13. .withParams(SEARCH_PARAM)
  14. .build();
  15. R<SearchResults> respSearch = milvusClient.search(searchParam);
  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: 2
  8. The boolean expression used to filter attribute []: word_count <= 11000
  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]:
参数 说明
data 用于搜索的向量。
anns_field 要搜索的 field 名称。
params 该索引特有的搜索参数。详细信息请参考 向量索引
limit 输出向量结果数。
expr 用于过滤属性的布尔表达式。有关详细信息,请参考 布尔表达式规则
partition_names (optional) 要搜索的 partition 名称列表。
output_fields (optional) 返回的 field 名称。当前版本不支持 Vector filed 。
timeout (optional) 允许 RPC 的持续时间(以秒为单位)。当设置为 None 时,客户端等待服务器响应或者发生错误。
round_decimal (optional) 返回距离的小数位数。
参数 说明
collection_name 要搜索的 collection 名称。
search_params 用于搜索的参数(对象)。
vectors 用于搜索的向量。
vector_type 二进制型或浮点型向量的预检查。二进制型向量为100 ,浮点型向量为101
partition_names (optional) 要搜索的 partition 名称列表。
expr (optional) 用于过滤属性的布尔表达式。有关详细信息,请参考 布尔表达式规则
output_fields (optional) 返回的 field 名称。当前版本不支持 Vector field 。
参数 说明 选项
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 该索引特有的搜索参数。 详细信息请参考 向量索引
ctx 控制调用 API 的 Context。 N/A
CollectionName 要加载的 collection 名称。 N/A
partitionNames 要加载的 partition 名称列表。如果将其置空,将搜索所有的 partition 。 N/A
expr 用于过滤属性的布尔表达式。 有关详细信息,请参考 布尔表达式规则
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 。
TopK 输出向量结果数。 N/A
Vectors 用于搜索的向量。 N/A
VectorFieldName 要搜索的 field 名称。 N/A
Expr 用于过滤属性的布尔表达式。 有关详细信息,请参考 布尔表达式规则
Params 该索引特有的搜索参数。 详细信息请参考 向量索引
选项 全称 说明
—help n/a 显示使用命令的帮助。

检查返回的结果。

{{fragments/multiple_code.md}}

  1. assert len(res) == 1
  2. hits = res[0]
  3. assert len(hits) == 2
  4. print(f"- Total hits: {len(hits)}, hits ids: {hits.ids} ")
  5. print(f"- Top1 hit id: {hits[0].id}, distance: {hits[0].distance}, score: {hits[0].score} ")
  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.

更多内容