UpsertExample.java 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  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.v2;
  20. import com.google.gson.Gson;
  21. import com.google.gson.JsonObject;
  22. import io.milvus.v1.CommonUtils;
  23. import io.milvus.v2.client.ConnectConfig;
  24. import io.milvus.v2.client.MilvusClientV2;
  25. import io.milvus.v2.common.ConsistencyLevel;
  26. import io.milvus.v2.common.DataType;
  27. import io.milvus.v2.common.IndexParam;
  28. import io.milvus.v2.service.collection.request.AddFieldReq;
  29. import io.milvus.v2.service.collection.request.CreateCollectionReq;
  30. import io.milvus.v2.service.collection.request.DropCollectionReq;
  31. import io.milvus.v2.service.vector.request.InsertReq;
  32. import io.milvus.v2.service.vector.request.QueryReq;
  33. import io.milvus.v2.service.vector.request.UpsertReq;
  34. import io.milvus.v2.service.vector.response.InsertResp;
  35. import io.milvus.v2.service.vector.response.QueryResp;
  36. import io.milvus.v2.service.vector.response.UpsertResp;
  37. import java.util.*;
  38. public class UpsertExample {
  39. private static final MilvusClientV2 client;
  40. static {
  41. client = new MilvusClientV2(ConnectConfig.builder()
  42. .uri("http://localhost:19530")
  43. .build());
  44. }
  45. private static final String COLLECTION_NAME = "java_sdk_example_upsert_v2";
  46. private static final String ID_FIELD = "pk";
  47. private static final String VECTOR_FIELD = "vector";
  48. private static final String TEXT_FIELD = "text";
  49. private static final Integer VECTOR_DIM = 128;
  50. private static List<Object> createCollection(boolean autoID) {
  51. // Drop collection if exists
  52. client.dropCollection(DropCollectionReq.builder()
  53. .collectionName(COLLECTION_NAME)
  54. .build());
  55. // Create collection
  56. CreateCollectionReq.CollectionSchema collectionSchema = CreateCollectionReq.CollectionSchema.builder()
  57. .build();
  58. collectionSchema.addField(AddFieldReq.builder()
  59. .fieldName(ID_FIELD)
  60. .dataType(DataType.Int64)
  61. .isPrimaryKey(Boolean.TRUE)
  62. .autoID(autoID)
  63. .build());
  64. collectionSchema.addField(AddFieldReq.builder()
  65. .fieldName(VECTOR_FIELD)
  66. .dataType(DataType.FloatVector)
  67. .dimension(VECTOR_DIM)
  68. .build());
  69. collectionSchema.addField(AddFieldReq.builder()
  70. .fieldName(TEXT_FIELD)
  71. .dataType(DataType.VarChar)
  72. .maxLength(100)
  73. .build());
  74. List<IndexParam> indexes = new ArrayList<>();
  75. indexes.add(IndexParam.builder()
  76. .fieldName(VECTOR_FIELD)
  77. .indexType(IndexParam.IndexType.FLAT)
  78. .metricType(IndexParam.MetricType.COSINE)
  79. .build());
  80. CreateCollectionReq requestCreate = CreateCollectionReq.builder()
  81. .collectionName(COLLECTION_NAME)
  82. .collectionSchema(collectionSchema)
  83. .indexParams(indexes)
  84. .consistencyLevel(ConsistencyLevel.BOUNDED)
  85. .build();
  86. client.createCollection(requestCreate);
  87. System.out.println("\nCollection created with autoID = " + autoID);
  88. // Insert rows
  89. Gson gson = new Gson();
  90. List<JsonObject> rows = new ArrayList<>();
  91. for (int i = 0; i < 100; i++) {
  92. JsonObject row = new JsonObject();
  93. if (!autoID) {
  94. row.addProperty(ID_FIELD, i);
  95. }
  96. List<Float> vector = CommonUtils.generateFloatVector(VECTOR_DIM);
  97. row.add(VECTOR_FIELD, gson.toJsonTree(vector));
  98. row.addProperty(TEXT_FIELD, String.format("text_%d", i));
  99. rows.add(row);
  100. }
  101. InsertResp resp = client.insert(InsertReq.builder()
  102. .collectionName(COLLECTION_NAME)
  103. .data(rows)
  104. .build());
  105. return resp.getPrimaryKeys();
  106. }
  107. private static void queryWithExpr(String expr) {
  108. QueryResp queryRet = client.query(QueryReq.builder()
  109. .collectionName(COLLECTION_NAME)
  110. .filter(expr)
  111. .outputFields(Arrays.asList(ID_FIELD, TEXT_FIELD))
  112. .consistencyLevel(ConsistencyLevel.STRONG)
  113. .build());
  114. System.out.println("\nQuery with expression: " + expr);
  115. List<QueryResp.QueryResult> records = queryRet.getQueryResults();
  116. for (QueryResp.QueryResult record : records) {
  117. System.out.println(record.getEntity());
  118. }
  119. }
  120. private static void doUpsert(boolean autoID) {
  121. // if autoID is true, the collection primary key is auto-generated by server
  122. List<Object> ids = createCollection(autoID);
  123. // query before upsert
  124. Long testID = (Long)ids.get(1);
  125. String filter = String.format("%s == %d", ID_FIELD, testID);
  126. queryWithExpr(filter);
  127. // upsert
  128. // the server will return a new primary key, the old entity is deleted,
  129. // and a new entity is created with the new primary key
  130. Gson gson = new Gson();
  131. JsonObject row = new JsonObject();
  132. row.addProperty(ID_FIELD, testID);
  133. List<Float> vector = CommonUtils.generateFloatVector(VECTOR_DIM);
  134. row.add(VECTOR_FIELD, gson.toJsonTree(vector));
  135. row.addProperty(TEXT_FIELD, "this field has been updated");
  136. UpsertResp upsertResp = client.upsert(UpsertReq.builder()
  137. .collectionName(COLLECTION_NAME)
  138. .data(Collections.singletonList(row))
  139. .build());
  140. List<Object> newIds = upsertResp.getPrimaryKeys();
  141. Long newID = (Long)newIds.get(0);
  142. System.out.println("\nUpsert done");
  143. // query after upsert
  144. filter = String.format("%s == %d", ID_FIELD, newID);
  145. queryWithExpr(filter);
  146. }
  147. public static void main(String[] args) {
  148. doUpsert(true);
  149. doUpsert(false);
  150. client.close();
  151. }
  152. }