SparseVectorExample.java 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  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.SearchReq;
  34. import io.milvus.v2.service.vector.request.data.SparseFloatVec;
  35. import io.milvus.v2.service.vector.response.QueryResp;
  36. import io.milvus.v2.service.vector.response.SearchResp;
  37. import java.util.*;
  38. public class SparseVectorExample {
  39. private static final String COLLECTION_NAME = "java_sdk_example_sparse_vector_v2";
  40. private static final String ID_FIELD = "id";
  41. private static final String VECTOR_FIELD = "vector";
  42. public static void main(String[] args) {
  43. ConnectConfig config = ConnectConfig.builder()
  44. .uri("http://localhost:19530")
  45. .build();
  46. MilvusClientV2 client = new MilvusClientV2(config);
  47. // Drop collection if exists
  48. client.dropCollection(DropCollectionReq.builder()
  49. .collectionName(COLLECTION_NAME)
  50. .build());
  51. // Create collection
  52. CreateCollectionReq.CollectionSchema collectionSchema = CreateCollectionReq.CollectionSchema.builder()
  53. .build();
  54. collectionSchema.addField(AddFieldReq.builder()
  55. .fieldName(ID_FIELD)
  56. .dataType(DataType.Int64)
  57. .isPrimaryKey(Boolean.TRUE)
  58. .build());
  59. collectionSchema.addField(AddFieldReq.builder()
  60. .fieldName(VECTOR_FIELD)
  61. .dataType(DataType.SparseFloatVector)
  62. .build());
  63. List<IndexParam> indexes = new ArrayList<>();
  64. indexes.add(IndexParam.builder()
  65. .fieldName(VECTOR_FIELD)
  66. .indexType(IndexParam.IndexType.SPARSE_WAND)
  67. .metricType(IndexParam.MetricType.IP)
  68. .build());
  69. CreateCollectionReq requestCreate = CreateCollectionReq.builder()
  70. .collectionName(COLLECTION_NAME)
  71. .collectionSchema(collectionSchema)
  72. .indexParams(indexes)
  73. .consistencyLevel(ConsistencyLevel.BOUNDED)
  74. .build();
  75. client.createCollection(requestCreate);
  76. System.out.println("Collection created");
  77. // Insert entities by rows
  78. int rowCount = 10000;
  79. List<JsonObject> rows = new ArrayList<>();
  80. Gson gson = new Gson();
  81. List<SortedMap<Long, Float>> vectors = new ArrayList<>();
  82. for (long i = 0L; i < rowCount; ++i) {
  83. JsonObject row = new JsonObject();
  84. row.addProperty(ID_FIELD, i);
  85. SortedMap<Long, Float> vector = CommonUtils.generateSparseVector();
  86. vectors.add(vector);
  87. row.add(VECTOR_FIELD, gson.toJsonTree(vector));
  88. rows.add(row);
  89. }
  90. client.insert(InsertReq.builder()
  91. .collectionName(COLLECTION_NAME)
  92. .data(rows)
  93. .build());
  94. // Get row count, set ConsistencyLevel.STRONG to sync the data to query node so that data is visible
  95. QueryResp countR = client.query(QueryReq.builder()
  96. .collectionName(COLLECTION_NAME)
  97. .filter("")
  98. .outputFields(Collections.singletonList("count(*)"))
  99. .consistencyLevel(ConsistencyLevel.STRONG)
  100. .build());
  101. System.out.printf("%d rows persisted\n", (long)countR.getQueryResults().get(0).getEntity().get("count(*)"));
  102. // Pick some vectors from the inserted vectors to search
  103. // Ensure the returned top1 item's ID should be equal to target vector's ID
  104. for (int i = 0; i < 10; i++) {
  105. Random ran = new Random();
  106. int k = ran.nextInt(rowCount);
  107. SortedMap<Long, Float> targetVector = vectors.get(k);
  108. Map<String,Object> params = new HashMap<>();
  109. params.put("drop_ratio_search",0.2);
  110. SearchResp searchResp = client.search(SearchReq.builder()
  111. .collectionName(COLLECTION_NAME)
  112. .data(Collections.singletonList(new SparseFloatVec(targetVector)))
  113. .annsField(VECTOR_FIELD)
  114. .outputFields(Collections.singletonList(VECTOR_FIELD))
  115. .searchParams(params)
  116. .topK(3)
  117. .build());
  118. // The search() allows multiple target vectors to search in a batch.
  119. // Here we only input one vector to search, get the result of No.0 vector to check
  120. List<List<SearchResp.SearchResult>> searchResults = searchResp.getSearchResults();
  121. List<SearchResp.SearchResult> results = searchResults.get(0);
  122. System.out.printf("The result of No.%d target vector:\n", i);
  123. for (SearchResp.SearchResult result : results) {
  124. System.out.println(result.getEntity());
  125. }
  126. SearchResp.SearchResult firstResult = results.get(0);
  127. if ((long)firstResult.getId() != k) {
  128. throw new RuntimeException(String.format("The top1 ID %d is not equal to target vector's ID %d",
  129. firstResult.getId(), k));
  130. }
  131. SortedMap<Long, Float> sparse = (SortedMap<Long, Float>) firstResult.getEntity().get(VECTOR_FIELD);
  132. if (!sparse.equals(targetVector)) {
  133. throw new RuntimeException("The query result is incorrect");
  134. }
  135. }
  136. System.out.println("Search result is correct");
  137. // Retrieve some data
  138. int n = 99;
  139. QueryResp queryResp = client.query(QueryReq.builder()
  140. .collectionName(COLLECTION_NAME)
  141. .filter(String.format("id == %d", n))
  142. .outputFields(Collections.singletonList(VECTOR_FIELD))
  143. .build());
  144. List<QueryResp.QueryResult> queryResults = queryResp.getQueryResults();
  145. if (queryResults.isEmpty()) {
  146. throw new RuntimeException("The query result is empty");
  147. } else {
  148. SortedMap<Long, Float> sparse = (SortedMap<Long, Float>) queryResults.get(0).getEntity().get(VECTOR_FIELD);
  149. if (!sparse.equals(vectors.get(n))) {
  150. throw new RuntimeException("The query result is incorrect");
  151. }
  152. }
  153. System.out.println("Query result is correct");
  154. // Drop the collection if you don't need the collection anymore
  155. client.dropCollection(DropCollectionReq.builder()
  156. .collectionName(COLLECTION_NAME)
  157. .build());
  158. client.close();
  159. }
  160. }