# 查询向量

Milvus 支持在集合或分区中查询向量。

## 在集合中查询向量

1. 创建搜索参数 DSL。

``````# This DSL searches for topk `entities` that are
# closest to vectors[:1] searched by `IVF_FLAT` index with `nprobe = 10` and `metric_type = L2`,
# AND field "A" in [1, 2, 5],
# AND field "B" greater than 1 less than 100
>>> dsl = {
...     "bool": {
...         "must":[
...             {
...                 "term": {"A": [1, 2, 5]}
...             },
...             {
...                 "range": {"B": {"GT": 1, "LT": 100}}
...             },
...             {
...                 "vector": {
...                    "Vec": {"topk": 10, "query": vectors[:1], "metric_type": "L2", "params": {"nprobe": 10}}
...                 }
...             }
...         ]
...     }
... }
``````
``````// Basic hybrid search:
// Let's say we have a film with its `embedding` and we want to find `top1` film that is
// most similar to it by L2 metric_type (Euclidean Distance).
// In addition to vector similarities, we also want to filter films such that:
// - `term` is 1, 2, or 5,
// - `duration` larger than 250 minutes.
List<List<Float>> queryEmbedding = /* your query vectors */;
final long topK = 10;
String dsl = String.format(
"{\"bool\": {"
+ "\"must\": [{"
+ "    \"range\": {"
+ "        \"A\": {\"GT\": 250}" // "GT" for greater than
+ "    }},{"
+ "    \"term\": {"
+ "        \"B\": [1, 5, 10]" // "term" is a list
+ "    }},{"
+ "    \"vector\": {"
+ "        \"embedding\": {"
+ "            \"topk\": %d, \"metric_type\": \"L2\", \"type\": \"float\", \"query\": %s"
+ "    }}}]}}", topK, queryEmbedding.toString());
``````
• `top_k` 指的是向量空间中距离目标向量最近的 k 个向量。
• `top_k` 的范围为：[1, 16384]。
• 对于不同的索引类型，搜索所需参数也有区别。所有的搜索参数都必须赋值。详细信息请参考 Milvus 索引类型
2. 进行搜索：

``````>>> client.search('test01', dsl)
``````
``````SearchParam searchParam = SearchParam
.create(collectionName)
.setDsl(dsl);

SearchResult searchResult = client.search(searchParam);
``````

你也可以指定搜索结果中返回指定列的值，此处我们获取字段 `B` 的值：

``````>>> client.search('test01', dsl, fields=["B"])
``````
``````SearchParam searchParam = SearchParam
.create(collectionName)
.setDsl(dsl)
.setParamsInJson("{\"fields\": [\"B\"]}");
SearchResult searchResult = client.search(searchParam);
``````

## 在分区中查询向量

``````>>> client.search('test01', dsl, partition_tags=['tag01'])
``````
``````setPartitionTags​(java.util.List<java.lang.String> partitionTags);
``````

## 常见问题

Milvus 是否支持 “边插入边查询” ？ 支持。

• CPU 版 Milvus 会对数据段读取任务和段内查询任务进行流水线处理。
• GPU 版 Milvus 会在 CPU 版的基础上，将多个数据段分配给各个 GPU 处理。