GeneralExample.java 22 KB

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