SimpleExample.java 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  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 io.milvus.client.MilvusServiceClient;
  22. import io.milvus.grpc.*;
  23. import io.milvus.param.*;
  24. import io.milvus.param.collection.*;
  25. import io.milvus.param.dml.*;
  26. import io.milvus.param.index.*;
  27. import io.milvus.response.*;
  28. import java.util.*;
  29. public class SimpleExample {
  30. private static final String COLLECTION_NAME = "java_sdk_example_simple";
  31. private static final String ID_FIELD = "book_id";
  32. private static final String VECTOR_FIELD = "book_intro";
  33. private static final String TITLE_FIELD = "book_title";
  34. private static final Integer VECTOR_DIM = 4;
  35. public static void main(String[] args) {
  36. // Connect to Milvus server. Replace the "localhost" and port with your Milvus server address.
  37. MilvusServiceClient milvusClient = new MilvusServiceClient(ConnectParam.newBuilder()
  38. .withHost("localhost")
  39. .withPort(19530)
  40. .build());
  41. // set log level, only show errors
  42. milvusClient.setLogLevel(LogLevel.Error);
  43. // Define fields
  44. List<FieldType> fieldsSchema = Arrays.asList(
  45. FieldType.newBuilder()
  46. .withName(ID_FIELD)
  47. .withDataType(DataType.Int64)
  48. .withPrimaryKey(true)
  49. .withAutoID(false)
  50. .build(),
  51. FieldType.newBuilder()
  52. .withName(VECTOR_FIELD)
  53. .withDataType(DataType.FloatVector)
  54. .withDimension(VECTOR_DIM)
  55. .build(),
  56. FieldType.newBuilder()
  57. .withName(TITLE_FIELD)
  58. .withDataType(DataType.VarChar)
  59. .withMaxLength(64)
  60. .build()
  61. );
  62. // Create the collection with 3 fields
  63. R<RpcStatus> ret = milvusClient.createCollection(CreateCollectionParam.newBuilder()
  64. .withCollectionName(COLLECTION_NAME)
  65. .withFieldTypes(fieldsSchema)
  66. .build());
  67. if (ret.getStatus() != R.Status.Success.getCode()) {
  68. throw new RuntimeException("Failed to create collection! Error: " + ret.getMessage());
  69. }
  70. // Specify an index type on the vector field.
  71. ret = milvusClient.createIndex(CreateIndexParam.newBuilder()
  72. .withCollectionName(COLLECTION_NAME)
  73. .withFieldName(VECTOR_FIELD)
  74. .withIndexType(IndexType.FLAT)
  75. .withMetricType(MetricType.L2)
  76. .build());
  77. if (ret.getStatus() != R.Status.Success.getCode()) {
  78. throw new RuntimeException("Failed to create index on vector field! Error: " + ret.getMessage());
  79. }
  80. // Specify an index type on the varchar field.
  81. ret = milvusClient.createIndex(CreateIndexParam.newBuilder()
  82. .withCollectionName(COLLECTION_NAME)
  83. .withFieldName(TITLE_FIELD)
  84. .withIndexType(IndexType.TRIE)
  85. .build());
  86. if (ret.getStatus() != R.Status.Success.getCode()) {
  87. throw new RuntimeException("Failed to create index on varchar field! Error: " + ret.getMessage());
  88. }
  89. // Call loadCollection() to enable automatically loading data into memory for searching
  90. milvusClient.loadCollection(LoadCollectionParam.newBuilder()
  91. .withCollectionName(COLLECTION_NAME)
  92. .build());
  93. System.out.println("Collection created");
  94. // Insert 10 records into the collection
  95. List<JSONObject> rows = new ArrayList<>();
  96. for (long i = 1L; i <= 10; ++i) {
  97. JSONObject row = new JSONObject();
  98. row.put(ID_FIELD, i);
  99. List<Float> vector = Arrays.asList((float)i, (float)i, (float)i, (float)i);
  100. row.put(VECTOR_FIELD, vector);
  101. row.put(TITLE_FIELD, "Tom and Jerry " + i);
  102. rows.add(row);
  103. }
  104. R<MutationResult> insertRet = milvusClient.insert(InsertParam.newBuilder()
  105. .withCollectionName(COLLECTION_NAME)
  106. .withRows(rows)
  107. .build());
  108. if (insertRet.getStatus() != R.Status.Success.getCode()) {
  109. throw new RuntimeException("Failed to insert! Error: " + insertRet.getMessage());
  110. }
  111. // Call flush to make sure the inserted records are consumed by Milvus server, so that the records
  112. // be searchable immediately. Just a special action in this example.
  113. // In practice, you don't need to call flush() frequently.
  114. milvusClient.flush(FlushParam.newBuilder()
  115. .addCollectionName(COLLECTION_NAME)
  116. .build());
  117. System.out.println("10 entities inserted");
  118. // Construct a vector to search top5 similar records, return the book title for us.
  119. // This vector is equal to the No.3 record, we suppose the No.3 record is the most similar.
  120. List<Float> vector = Arrays.asList(3.0f, 3.0f, 3.0f, 3.0f);
  121. R<SearchResults> searchRet = milvusClient.search(SearchParam.newBuilder()
  122. .withCollectionName(COLLECTION_NAME)
  123. .withMetricType(MetricType.L2)
  124. .withTopK(5)
  125. .withFloatVectors(Arrays.asList(vector))
  126. .withVectorFieldName(VECTOR_FIELD)
  127. .withParams("{}")
  128. .addOutField(TITLE_FIELD)
  129. .build());
  130. if (searchRet.getStatus() != R.Status.Success.getCode()) {
  131. throw new RuntimeException("Failed to search! Error: " + searchRet.getMessage());
  132. }
  133. // The search() allows multiple target vectors to search in a batch.
  134. // Here we only input one vector to search, get the result of No.0 vector to print out
  135. SearchResultsWrapper resultsWrapper = new SearchResultsWrapper(searchRet.getData().getResults());
  136. List<SearchResultsWrapper.IDScore> scores = resultsWrapper.getIDScore(0);
  137. System.out.println("The result of No.0 target vector:");
  138. for (SearchResultsWrapper.IDScore score:scores) {
  139. System.out.println(score);
  140. }
  141. // drop the collection if you don't need the collection anymore
  142. milvusClient.dropCollection(DropCollectionParam.newBuilder()
  143. .withCollectionName(COLLECTION_NAME)
  144. .build());
  145. }
  146. }