HighLevelExample.java 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  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.common.collect.Lists;
  22. import io.milvus.client.MilvusServiceClient;
  23. import io.milvus.common.clientenum.ConsistencyLevelEnum;
  24. import io.milvus.common.utils.JacksonUtils;
  25. import io.milvus.common.utils.VectorUtils;
  26. import io.milvus.grpc.*;
  27. import io.milvus.param.*;
  28. import io.milvus.param.collection.*;
  29. import io.milvus.param.highlevel.collection.response.ListCollectionsResponse;
  30. import io.milvus.param.highlevel.collection.CreateSimpleCollectionParam;
  31. import io.milvus.param.highlevel.collection.ListCollectionsParam;
  32. import io.milvus.param.highlevel.dml.*;
  33. import io.milvus.param.highlevel.dml.response.*;
  34. import io.milvus.response.*;
  35. import java.util.ArrayList;
  36. import java.util.List;
  37. import java.util.Random;
  38. ///////////////////////////////////////////////////////////////////////////////////////////////////////////
  39. // Note:
  40. // Due do a technical limitation, the Milvus 2.0 not allow to create multi-vector-fields within a collection.
  41. // So this example only create a single vector field in the collection, but we suppose the next version
  42. // should support this function.
  43. ///////////////////////////////////////////////////////////////////////////////////////////////////////////
  44. public class HighLevelExample {
  45. private static final MilvusServiceClient milvusClient;
  46. static {
  47. ConnectParam connectParam = ConnectParam.newBuilder()
  48. .withHost("localhost")
  49. .withPort(19530)
  50. .withAuthorization("root","Milvus")
  51. .build();
  52. milvusClient = new MilvusServiceClient(connectParam);
  53. }
  54. private static final String COLLECTION_NAME = "java_sdk_example_hl";
  55. private static final String ID_FIELD = "userID";
  56. private static final String VECTOR_FIELD = "userFace";
  57. private static final String USER_JSON_FIELD = "userJson";
  58. private static final Integer VECTOR_DIM = 36;
  59. private static final String AGE_FIELD = "userAge";
  60. private static final String INDEX_NAME = "userFaceIndex";
  61. private static final IndexType INDEX_TYPE = IndexType.IVF_FLAT;
  62. private static final String INDEX_PARAM = "{\"nlist\":128}";
  63. private static final String INT32_FIELD_NAME = "int32";
  64. private static final String INT64_FIELD_NAME = "int64";
  65. private static final String VARCHAR_FIELD_NAME = "varchar";
  66. private static final String BOOL_FIELD_NAME = "bool";
  67. private static final String FLOAT_FIELD_NAME = "float";
  68. private static final String DOUBLE_FIELD_NAME = "double";
  69. private static void handleResponseStatus(R<?> r) {
  70. if (r.getStatus() != R.Status.Success.getCode()) {
  71. throw new RuntimeException(r.getMessage());
  72. }
  73. }
  74. private R<DescribeCollectionResponse> describeCollection() {
  75. System.out.println("========== describeCollection() ==========");
  76. R<DescribeCollectionResponse> response = milvusClient.describeCollection(DescribeCollectionParam.newBuilder()
  77. .withCollectionName(COLLECTION_NAME)
  78. .build());
  79. handleResponseStatus(response);
  80. DescCollResponseWrapper wrapper = new DescCollResponseWrapper(response.getData());
  81. System.out.println(wrapper);
  82. return response;
  83. }
  84. private List<Float> generateFloatVector() {
  85. Random ran = new Random();
  86. List<Float> vector = new ArrayList<>();
  87. for (int i = 0; i < VECTOR_DIM; ++i) {
  88. vector.add(ran.nextFloat());
  89. }
  90. return vector;
  91. }
  92. // >>>>>>>>>>>>> high level api
  93. private R<RpcStatus> createCollection() {
  94. System.out.println("========== high level createCollection ==========");
  95. CreateSimpleCollectionParam createSimpleCollectionParam = CreateSimpleCollectionParam.newBuilder()
  96. .withCollectionName(COLLECTION_NAME)
  97. .withDimension(VECTOR_DIM)
  98. .withPrimaryField(ID_FIELD)
  99. .withVectorField(VECTOR_FIELD)
  100. .withAutoId(true)
  101. .build();
  102. R<RpcStatus> response = milvusClient.createCollection(createSimpleCollectionParam);
  103. handleResponseStatus(response);
  104. System.out.println(JacksonUtils.toJsonString(response.getData()));
  105. return response;
  106. }
  107. private R<ListCollectionsResponse> listCollections() {
  108. System.out.println("========== high level listCollections ==========");
  109. ListCollectionsParam listCollectionsParam = ListCollectionsParam.newBuilder()
  110. .build();
  111. R<ListCollectionsResponse> response = milvusClient.listCollections(listCollectionsParam);
  112. handleResponseStatus(response);
  113. System.out.println(response);
  114. return response;
  115. }
  116. private R<InsertResponse> insertRows(int rowCount) {
  117. System.out.println("========== high level insertRows ==========");
  118. List<JSONObject> rowsData = new ArrayList<>();
  119. Random ran = new Random();
  120. for (long i = 0L; i < rowCount; ++i) {
  121. JSONObject row = new JSONObject();
  122. row.put(AGE_FIELD, ran.nextInt(99));
  123. row.put(VECTOR_FIELD, generateFloatVector());
  124. // $meta if collection EnableDynamicField, you can input this field not exist in schema, else deny
  125. row.put(INT32_FIELD_NAME, ran.nextInt());
  126. row.put(INT64_FIELD_NAME, ran.nextLong());
  127. row.put(VARCHAR_FIELD_NAME, "测试varchar");
  128. row.put(FLOAT_FIELD_NAME, ran.nextFloat());
  129. row.put(DOUBLE_FIELD_NAME, ran.nextDouble());
  130. row.put(BOOL_FIELD_NAME, ran.nextBoolean());
  131. // $json
  132. JSONObject jsonObject = new JSONObject();
  133. jsonObject.put(INT32_FIELD_NAME, ran.nextInt());
  134. jsonObject.put(INT64_FIELD_NAME, ran.nextLong());
  135. jsonObject.put(VARCHAR_FIELD_NAME, "测试varchar");
  136. jsonObject.put(FLOAT_FIELD_NAME, ran.nextFloat());
  137. jsonObject.put(DOUBLE_FIELD_NAME, ran.nextDouble());
  138. jsonObject.put(BOOL_FIELD_NAME, ran.nextBoolean());
  139. row.put(USER_JSON_FIELD, jsonObject);
  140. rowsData.add(row);
  141. }
  142. InsertRowsParam insertRowsParam = InsertRowsParam.newBuilder()
  143. .withCollectionName(COLLECTION_NAME)
  144. .withRows(rowsData)
  145. .build();
  146. R<InsertResponse> response = milvusClient.insert(insertRowsParam);
  147. handleResponseStatus(response);
  148. System.out.println("insertCount: " + response.getData().getInsertCount());
  149. System.out.println("insertIds: " + response.getData().getInsertIds());
  150. return response;
  151. }
  152. private R<DeleteResponse> delete(List<?> ids) {
  153. System.out.println("========== high level insertRows ==========");
  154. DeleteIdsParam deleteIdsParam = DeleteIdsParam.newBuilder()
  155. .withCollectionName(COLLECTION_NAME)
  156. .withPrimaryIds(ids)
  157. .build();
  158. R<DeleteResponse> response = milvusClient.delete(deleteIdsParam);
  159. handleResponseStatus(response);
  160. System.out.println(response);
  161. return response;
  162. }
  163. private R<GetResponse> get(List<?> ids) {
  164. System.out.println("========== high level get ==========");
  165. GetIdsParam getParam = GetIdsParam.newBuilder()
  166. .withCollectionName(COLLECTION_NAME)
  167. .withPrimaryIds(ids)
  168. .build();
  169. R<GetResponse> response = milvusClient.get(getParam);
  170. handleResponseStatus(response);
  171. for (QueryResultsWrapper.RowRecord rowRecord : response.getData().getRowRecords()) {
  172. System.out.println(rowRecord);
  173. }
  174. return response;
  175. }
  176. private R<SearchResponse> searchSimple(String filter) {
  177. System.out.println("========== high level search ==========");
  178. SearchSimpleParam searchSimpleParam = SearchSimpleParam.newBuilder()
  179. .withCollectionName(COLLECTION_NAME)
  180. .withVectors(generateFloatVector())
  181. .withFilter(filter)
  182. .withLimit(100L)
  183. .withOffset(0L)
  184. .withOutputFields(Lists.newArrayList("int32", "int64"))
  185. .withConsistencyLevel(ConsistencyLevelEnum.STRONG)
  186. .build();
  187. R<SearchResponse> response = milvusClient.search(searchSimpleParam);
  188. handleResponseStatus(response);
  189. for (QueryResultsWrapper.RowRecord rowRecord : response.getData().getRowRecords(0)) {
  190. System.out.println(rowRecord);
  191. }
  192. return response;
  193. }
  194. private R<QueryResponse> querySimple(String filter) {
  195. milvusClient.flush(FlushParam.newBuilder().addCollectionName(COLLECTION_NAME).build());
  196. System.out.println("========== high level query ==========");
  197. QuerySimpleParam querySimpleParam = QuerySimpleParam.newBuilder()
  198. .withCollectionName(COLLECTION_NAME)
  199. .withFilter(filter)
  200. .withOutputFields(Lists.newArrayList("int32", "int64"))
  201. .withLimit(100L)
  202. .withOffset(0L)
  203. .withConsistencyLevel(ConsistencyLevelEnum.STRONG)
  204. .build();
  205. R<QueryResponse> response = milvusClient.query(querySimpleParam);
  206. handleResponseStatus(response);
  207. for (QueryResultsWrapper.RowRecord rowRecord : response.getData().getRowRecords()) {
  208. System.out.println(rowRecord);
  209. }
  210. return response;
  211. }
  212. public static void main(String[] args) {
  213. HighLevelExample example = new HighLevelExample();
  214. example.createCollection();
  215. example.listCollections();
  216. R<DescribeCollectionResponse> describeCollectionResponseR = example.describeCollection();
  217. DescCollResponseWrapper descCollResponseWrapper = new DescCollResponseWrapper(describeCollectionResponseR.getData());
  218. int dataCount = 5;
  219. R<InsertResponse> insertResponse = example.insertRows(dataCount);
  220. List<?> insertIds = insertResponse.getData().getInsertIds();
  221. example.get(insertIds);
  222. String expr = VectorUtils.convertPksExpr(insertIds, descCollResponseWrapper);
  223. example.querySimple(expr);
  224. example.searchSimple(expr);
  225. // Asynchronous deletion. A successful response does not guarantee immediate data deletion. Please wait for a certain period of time for the deletion operation to take effect.
  226. example.delete(insertIds);
  227. }
  228. }