GeneralExample.java 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  1. /*
  2. * Licensed to the Apache Software Foundation (ASF) under one
  3. * or more contributor license agreements. See the NOTICE file
  4. * distributed with this work for additional information
  5. * regarding copyright ownership. The ASF licenses this file
  6. * to you under the Apache License, Version 2.0 (the
  7. * "License"); you may not use this file except in compliance
  8. * with the License. You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing,
  13. * software distributed under the License is distributed on an
  14. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15. * KIND, either express or implied. See the License for the
  16. * specific language governing permissions and limitations
  17. * under the License.
  18. */
  19. package io.milvus;
  20. import com.alibaba.fastjson.JSONObject;
  21. import com.google.protobuf.ByteString;
  22. import io.milvus.client.MilvusServiceClient;
  23. import io.milvus.common.clientenum.ConsistencyLevelEnum;
  24. import io.milvus.common.utils.JacksonUtils;
  25. import io.milvus.grpc.*;
  26. import io.milvus.param.*;
  27. import io.milvus.param.collection.*;
  28. import io.milvus.param.control.ManualCompactParam;
  29. import io.milvus.param.dml.*;
  30. import io.milvus.param.index.*;
  31. import io.milvus.param.partition.*;
  32. import io.milvus.response.*;
  33. import java.util.*;
  34. import java.util.concurrent.TimeUnit;
  35. ///////////////////////////////////////////////////////////////////////////////////////////////////////////
  36. // Note:
  37. // Due do a technical limitation, the Milvus 2.0 not allow to create multi-vector-fields within a collection.
  38. // So this example only create a single vector field in the collection, but we suppose the next version
  39. // should support this function.
  40. ///////////////////////////////////////////////////////////////////////////////////////////////////////////
  41. public class GeneralExample {
  42. private static final MilvusServiceClient milvusClient;
  43. static {
  44. ConnectParam connectParam = ConnectParam.newBuilder()
  45. .withHost("localhost")
  46. .withPort(19530)
  47. .withAuthorization("root","Milvus")
  48. .build();
  49. milvusClient = new MilvusServiceClient(connectParam);
  50. }
  51. private static final String COLLECTION_NAME = "java_sdk_example_general";
  52. private static final String ID_FIELD = "userID";
  53. private static final String VECTOR_FIELD = "userFace";
  54. private static final Integer VECTOR_DIM = 64;
  55. private static final String AGE_FIELD = "userAge";
  56. private static final String INDEX_NAME = "userFaceIndex";
  57. private static final IndexType INDEX_TYPE = IndexType.IVF_FLAT;
  58. private static final String INDEX_PARAM = "{\"nlist\":128}";
  59. private static final Integer SEARCH_K = 5;
  60. private static final String SEARCH_PARAM = "{\"nprobe\":10}";
  61. private void handleResponseStatus(R<?> r) {
  62. if (r.getStatus() != R.Status.Success.getCode()) {
  63. throw new RuntimeException(r.getMessage());
  64. }
  65. }
  66. private R<RpcStatus> createCollection(long timeoutMilliseconds) {
  67. System.out.println("========== createCollection() ==========");
  68. FieldType fieldType1 = FieldType.newBuilder()
  69. .withName(ID_FIELD)
  70. .withDescription("user identification")
  71. .withDataType(DataType.Int64)
  72. .withPrimaryKey(true)
  73. .withAutoID(true)
  74. .build();
  75. FieldType fieldType2 = FieldType.newBuilder()
  76. .withName(VECTOR_FIELD)
  77. .withDescription("face embedding")
  78. .withDataType(DataType.FloatVector)
  79. .withDimension(VECTOR_DIM)
  80. .build();
  81. FieldType fieldType3 = FieldType.newBuilder()
  82. .withName(AGE_FIELD)
  83. .withDescription("user age")
  84. .withDataType(DataType.Int8)
  85. .build();
  86. CreateCollectionParam createCollectionReq = CreateCollectionParam.newBuilder()
  87. .withCollectionName(COLLECTION_NAME)
  88. .withDescription("customer info")
  89. .withShardsNum(2)
  90. .withEnableDynamicField(false)
  91. .addFieldType(fieldType1)
  92. .addFieldType(fieldType2)
  93. .addFieldType(fieldType3)
  94. .build();
  95. R<RpcStatus> response = milvusClient.withTimeout(timeoutMilliseconds, TimeUnit.MILLISECONDS)
  96. .createCollection(createCollectionReq);
  97. handleResponseStatus(response);
  98. System.out.println(response);
  99. return response;
  100. }
  101. private R<RpcStatus> dropCollection() {
  102. System.out.println("========== dropCollection() ==========");
  103. R<RpcStatus> response = milvusClient.dropCollection(DropCollectionParam.newBuilder()
  104. .withCollectionName(COLLECTION_NAME)
  105. .build());
  106. System.out.println(response);
  107. return response;
  108. }
  109. private boolean hasCollection() {
  110. System.out.println("========== hasCollection() ==========");
  111. R<Boolean> response = milvusClient.hasCollection(HasCollectionParam.newBuilder()
  112. .withCollectionName(COLLECTION_NAME)
  113. .build());
  114. handleResponseStatus(response);
  115. System.out.println(response);
  116. return response.getData().booleanValue();
  117. }
  118. private R<RpcStatus> loadCollection() {
  119. System.out.println("========== loadCollection() ==========");
  120. R<RpcStatus> response = milvusClient.loadCollection(LoadCollectionParam.newBuilder()
  121. .withCollectionName(COLLECTION_NAME)
  122. .build());
  123. handleResponseStatus(response);
  124. System.out.println(response);
  125. return response;
  126. }
  127. private R<RpcStatus> releaseCollection() {
  128. System.out.println("========== releaseCollection() ==========");
  129. R<RpcStatus> response = milvusClient.releaseCollection(ReleaseCollectionParam.newBuilder()
  130. .withCollectionName(COLLECTION_NAME)
  131. .build());
  132. handleResponseStatus(response);
  133. System.out.println(response);
  134. return response;
  135. }
  136. private R<DescribeCollectionResponse> describeCollection() {
  137. System.out.println("========== describeCollection() ==========");
  138. R<DescribeCollectionResponse> response = milvusClient.describeCollection(DescribeCollectionParam.newBuilder()
  139. .withCollectionName(COLLECTION_NAME)
  140. .build());
  141. handleResponseStatus(response);
  142. DescCollResponseWrapper wrapper = new DescCollResponseWrapper(response.getData());
  143. System.out.println(wrapper.toString());
  144. return response;
  145. }
  146. private R<GetCollectionStatisticsResponse> getCollectionStatistics() {
  147. // call flush() to flush the insert buffer to storage,
  148. // so that the getCollectionStatistics() can get correct number
  149. milvusClient.flush(FlushParam.newBuilder().addCollectionName(COLLECTION_NAME).build());
  150. System.out.println("========== getCollectionStatistics() ==========");
  151. R<GetCollectionStatisticsResponse> response = milvusClient.getCollectionStatistics(
  152. GetCollectionStatisticsParam.newBuilder()
  153. .withCollectionName(COLLECTION_NAME)
  154. .build());
  155. handleResponseStatus(response);
  156. GetCollStatResponseWrapper wrapper = new GetCollStatResponseWrapper(response.getData());
  157. System.out.println("Collection row count: " + wrapper.getRowCount());
  158. return response;
  159. }
  160. private R<ShowCollectionsResponse> showCollections() {
  161. System.out.println("========== showCollections() ==========");
  162. R<ShowCollectionsResponse> response = milvusClient.showCollections(ShowCollectionsParam.newBuilder()
  163. .build());
  164. handleResponseStatus(response);
  165. System.out.println(response);
  166. return response;
  167. }
  168. private R<RpcStatus> createPartition(String partitionName) {
  169. System.out.println("========== createPartition() ==========");
  170. R<RpcStatus> response = milvusClient.createPartition(CreatePartitionParam.newBuilder()
  171. .withCollectionName(COLLECTION_NAME)
  172. .withPartitionName(partitionName)
  173. .build());
  174. handleResponseStatus(response);
  175. System.out.println(response);
  176. return response;
  177. }
  178. private R<RpcStatus> dropPartition(String partitionName) {
  179. System.out.println("========== dropPartition() ==========");
  180. R<RpcStatus> response = milvusClient.dropPartition(DropPartitionParam.newBuilder()
  181. .withCollectionName(COLLECTION_NAME)
  182. .withPartitionName(partitionName)
  183. .build());
  184. handleResponseStatus(response);
  185. System.out.println(response);
  186. return response;
  187. }
  188. private R<Boolean> hasPartition(String partitionName) {
  189. System.out.println("========== hasPartition() ==========");
  190. R<Boolean> response = milvusClient.hasPartition(HasPartitionParam.newBuilder()
  191. .withCollectionName(COLLECTION_NAME)
  192. .withPartitionName(partitionName)
  193. .build());
  194. handleResponseStatus(response);
  195. System.out.println(response);
  196. return response;
  197. }
  198. private R<RpcStatus> releasePartition(String partitionName) {
  199. System.out.println("========== releasePartition() ==========");
  200. R<RpcStatus> response = milvusClient.releasePartitions(ReleasePartitionsParam.newBuilder()
  201. .withCollectionName(COLLECTION_NAME)
  202. .addPartitionName(partitionName)
  203. .build());
  204. handleResponseStatus(response);
  205. System.out.println(response);
  206. return response;
  207. }
  208. private R<ShowPartitionsResponse> showPartitions() {
  209. System.out.println("========== showPartitions() ==========");
  210. R<ShowPartitionsResponse> response = milvusClient.showPartitions(ShowPartitionsParam.newBuilder()
  211. .withCollectionName(COLLECTION_NAME)
  212. .build());
  213. handleResponseStatus(response);
  214. System.out.println(response);
  215. return response;
  216. }
  217. private R<RpcStatus> createIndex() {
  218. System.out.println("========== createIndex() ==========");
  219. // create index for scalar field
  220. R<RpcStatus> response = milvusClient.createIndex(CreateIndexParam.newBuilder()
  221. .withCollectionName(COLLECTION_NAME)
  222. .withFieldName(AGE_FIELD)
  223. .withIndexType(IndexType.STL_SORT)
  224. .withSyncMode(Boolean.TRUE)
  225. .build());
  226. handleResponseStatus(response);
  227. // create index for vector field
  228. response = milvusClient.createIndex(CreateIndexParam.newBuilder()
  229. .withCollectionName(COLLECTION_NAME)
  230. .withFieldName(VECTOR_FIELD)
  231. .withIndexName(INDEX_NAME)
  232. .withIndexType(INDEX_TYPE)
  233. .withMetricType(MetricType.L2)
  234. .withExtraParam(INDEX_PARAM)
  235. .withSyncMode(Boolean.TRUE)
  236. .build());
  237. handleResponseStatus(response);
  238. System.out.println(response);
  239. return response;
  240. }
  241. private R<RpcStatus> dropIndex() {
  242. System.out.println("========== dropIndex() ==========");
  243. R<RpcStatus> response = milvusClient.dropIndex(DropIndexParam.newBuilder()
  244. .withCollectionName(COLLECTION_NAME)
  245. .withIndexName(INDEX_NAME)
  246. .build());
  247. handleResponseStatus(response);
  248. System.out.println(response);
  249. return response;
  250. }
  251. private R<DescribeIndexResponse> describeIndex() {
  252. System.out.println("========== describeIndex() ==========");
  253. R<DescribeIndexResponse> response = milvusClient.describeIndex(DescribeIndexParam.newBuilder()
  254. .withCollectionName(COLLECTION_NAME)
  255. .withIndexName(INDEX_NAME)
  256. .build());
  257. handleResponseStatus(response);
  258. System.out.println(response);
  259. return response;
  260. }
  261. private R<GetIndexStateResponse> getIndexState() {
  262. System.out.println("========== getIndexState() ==========");
  263. R<GetIndexStateResponse> response = milvusClient.getIndexState(GetIndexStateParam.newBuilder()
  264. .withCollectionName(COLLECTION_NAME)
  265. .withIndexName(INDEX_NAME)
  266. .build());
  267. handleResponseStatus(response);
  268. System.out.println(response);
  269. return response;
  270. }
  271. private R<GetIndexBuildProgressResponse> getIndexBuildProgress() {
  272. System.out.println("========== getIndexBuildProgress() ==========");
  273. R<GetIndexBuildProgressResponse> response = milvusClient.getIndexBuildProgress(
  274. GetIndexBuildProgressParam.newBuilder()
  275. .withCollectionName(COLLECTION_NAME)
  276. .withIndexName(INDEX_NAME)
  277. .build());
  278. handleResponseStatus(response);
  279. System.out.println(response);
  280. return response;
  281. }
  282. private R<MutationResult> delete(String partitionName, String expr) {
  283. System.out.println("========== delete() ==========");
  284. DeleteParam build = DeleteParam.newBuilder()
  285. .withCollectionName(COLLECTION_NAME)
  286. .withPartitionName(partitionName)
  287. .withExpr(expr)
  288. .build();
  289. R<MutationResult> response = milvusClient.delete(build);
  290. handleResponseStatus(response);
  291. System.out.println(response.getData());
  292. return response;
  293. }
  294. private R<SearchResults> searchFace(String expr) {
  295. System.out.println("========== searchFace() ==========");
  296. long begin = System.currentTimeMillis();
  297. List<String> outFields = Collections.singletonList(AGE_FIELD);
  298. List<List<Float>> vectors = generateFloatVectors(5);
  299. SearchParam searchParam = SearchParam.newBuilder()
  300. .withCollectionName(COLLECTION_NAME)
  301. .withMetricType(MetricType.L2)
  302. .withOutFields(outFields)
  303. .withTopK(SEARCH_K)
  304. .withVectors(vectors)
  305. .withVectorFieldName(VECTOR_FIELD)
  306. .withExpr(expr)
  307. .withParams(SEARCH_PARAM)
  308. .withConsistencyLevel(ConsistencyLevelEnum.EVENTUALLY)
  309. .build();
  310. R<SearchResults> response = milvusClient.search(searchParam);
  311. long end = System.currentTimeMillis();
  312. long cost = (end - begin);
  313. System.out.println("Search time cost: " + cost + "ms");
  314. handleResponseStatus(response);
  315. SearchResultsWrapper wrapper = new SearchResultsWrapper(response.getData().getResults());
  316. for (int i = 0; i < vectors.size(); ++i) {
  317. System.out.println("Search result of No." + i);
  318. List<SearchResultsWrapper.IDScore> scores = wrapper.getIDScore(i);
  319. System.out.println(scores);
  320. System.out.println("Output field data for No." + i);
  321. System.out.println(wrapper.getFieldData(AGE_FIELD, i));
  322. }
  323. return response;
  324. }
  325. private R<QueryResults> query(String expr) {
  326. System.out.println("========== query() ==========");
  327. List<String> fields = Arrays.asList(ID_FIELD, AGE_FIELD);
  328. QueryParam test = QueryParam.newBuilder()
  329. .withCollectionName(COLLECTION_NAME)
  330. .withExpr(expr)
  331. .withOutFields(fields)
  332. .build();
  333. R<QueryResults> response = milvusClient.query(test);
  334. handleResponseStatus(response);
  335. QueryResultsWrapper wrapper = new QueryResultsWrapper(response.getData());
  336. System.out.println(ID_FIELD + ":" + wrapper.getFieldWrapper(ID_FIELD).getFieldData().toString());
  337. System.out.println(AGE_FIELD + ":" + wrapper.getFieldWrapper(AGE_FIELD).getFieldData().toString());
  338. System.out.println("Query row count: " + wrapper.getFieldWrapper(ID_FIELD).getRowCount());
  339. return response;
  340. }
  341. private R<ManualCompactionResponse> compact() {
  342. System.out.println("========== compact() ==========");
  343. R<ManualCompactionResponse> response = milvusClient.manualCompact(ManualCompactParam.newBuilder()
  344. .withCollectionName(COLLECTION_NAME)
  345. .build());
  346. handleResponseStatus(response);
  347. return response;
  348. }
  349. private R<MutationResult> insertColumns(String partitionName, int count) {
  350. System.out.println("========== insertColumns() ==========");
  351. List<List<Float>> vectors = generateFloatVectors(count);
  352. Random ran = new Random();
  353. List<Integer> ages = new ArrayList<>();
  354. for (long i = 0L; i < count; ++i) {
  355. ages.add(ran.nextInt(99));
  356. }
  357. List<InsertParam.Field> fields = new ArrayList<>();
  358. fields.add(new InsertParam.Field(AGE_FIELD, ages));
  359. fields.add(new InsertParam.Field(VECTOR_FIELD, vectors));
  360. InsertParam insertParam = InsertParam.newBuilder()
  361. .withCollectionName(COLLECTION_NAME)
  362. .withPartitionName(partitionName)
  363. .withFields(fields)
  364. .build();
  365. R<MutationResult> response = milvusClient.insert(insertParam);
  366. handleResponseStatus(response);
  367. return response;
  368. }
  369. private R<MutationResult> insertRows(String partitionName, int count) {
  370. System.out.println("========== insertRows() ==========");
  371. List<JSONObject> rowsData = new ArrayList<>();
  372. Random ran = new Random();
  373. for (long i = 0L; i < count; ++i) {
  374. JSONObject row = new JSONObject();
  375. row.put(AGE_FIELD, ran.nextInt(99));
  376. row.put(VECTOR_FIELD, generateFloatVector());
  377. rowsData.add(row);
  378. }
  379. InsertParam insertParam = InsertParam.newBuilder()
  380. .withCollectionName(COLLECTION_NAME)
  381. .withPartitionName(partitionName)
  382. .withRows(rowsData)
  383. .build();
  384. R<MutationResult> response = milvusClient.insert(insertParam);
  385. handleResponseStatus(response);
  386. return response;
  387. }
  388. private List<List<Float>> generateFloatVectors(int count) {
  389. Random ran = new Random();
  390. List<List<Float>> vectors = new ArrayList<>();
  391. for (int n = 0; n < count; ++n) {
  392. List<Float> vector = new ArrayList<>();
  393. for (int i = 0; i < VECTOR_DIM; ++i) {
  394. vector.add(ran.nextFloat());
  395. }
  396. vectors.add(vector);
  397. }
  398. return vectors;
  399. }
  400. private List<Float> generateFloatVector() {
  401. Random ran = new Random();
  402. List<Float> vector = new ArrayList<>();
  403. for (int i = 0; i < VECTOR_DIM; ++i) {
  404. vector.add(ran.nextFloat());
  405. }
  406. return vector;
  407. }
  408. public static void main(String[] args) {
  409. GeneralExample example = new GeneralExample();
  410. if (example.hasCollection()) {
  411. example.dropCollection();
  412. }
  413. example.createCollection(2000);
  414. example.hasCollection();
  415. example.describeCollection();
  416. example.showCollections();
  417. final String partitionName = "p1";
  418. example.createPartition(partitionName);
  419. example.hasPartition(partitionName);
  420. example.showPartitions();
  421. final int row_count = 10000;
  422. List<Long> deleteIds = new ArrayList<>();
  423. Random ran = new Random();
  424. for (int i = 0; i < 100; ++i) {
  425. // insertColumns
  426. R<MutationResult> result = example.insertColumns(partitionName, row_count);
  427. MutationResultWrapper wrapper = new MutationResultWrapper(result.getData());
  428. List<Long> ids = wrapper.getLongIDs();
  429. deleteIds.add(ids.get(ran.nextInt(row_count)));
  430. }
  431. // insertRows
  432. R<MutationResult> result = example.insertRows(partitionName, 10);
  433. MutationResultWrapper wrapper = new MutationResultWrapper(result.getData());
  434. long insertCount = wrapper.getInsertCount();
  435. List<Long> longIDs = wrapper.getLongIDs();
  436. System.out.println("complete insertRows, insertCount:" + insertCount + "; longIDs:" + longIDs);
  437. example.getCollectionStatistics();
  438. // Must create an index before load(), FLAT is brute-force search(no index)
  439. milvusClient.createIndex(CreateIndexParam.newBuilder()
  440. .withCollectionName(COLLECTION_NAME)
  441. .withFieldName(VECTOR_FIELD)
  442. .withIndexName(INDEX_NAME)
  443. .withIndexType(IndexType.FLAT)
  444. .withMetricType(MetricType.L2)
  445. .withExtraParam(INDEX_PARAM)
  446. .withSyncMode(Boolean.TRUE)
  447. .build());
  448. // loadCollection() must be called before search()
  449. example.loadCollection();
  450. System.out.println("Search without index");
  451. String searchExpr = AGE_FIELD + " > 50";
  452. example.searchFace(searchExpr);
  453. // must call releaseCollection() before re-create index
  454. example.releaseCollection();
  455. // re-create another index
  456. example.dropIndex();
  457. example.createIndex();
  458. example.describeIndex();
  459. example.getIndexBuildProgress();
  460. example.getIndexState();
  461. // loadCollection() must be called before search()
  462. example.loadCollection();
  463. System.out.println("Search with index");
  464. example.searchFace(searchExpr);
  465. String deleteExpr = ID_FIELD + " in " + deleteIds.toString();
  466. example.delete(partitionName, deleteExpr);
  467. String queryExpr = AGE_FIELD + " == 60";
  468. example.query(queryExpr);
  469. example.compact();
  470. example.getCollectionStatistics();
  471. example.releaseCollection();
  472. example.dropPartition(partitionName);
  473. example.dropIndex();
  474. example.dropCollection();
  475. }
  476. }