Prerequisites:
- Java Development Kit (JDK) 11 or later
- Apache Maven
- A running instance of Milvus
Setting Up the Project
First, set up a new Maven project. In the “pom.xml” file of your project, include the Milvus Java SDK dependency:
<groupId>io.milvus</groupId>
<artifactId>milvus-sdk-java</artifactId>
<version>2.2.x</version>
</dependency>
NOTE: For compatibility, ensure that the version matches the version of your Milvus instance.
Connect to the Milvus Server
To interact with Milvus, create an instance of “MilvusServiceClient”:
final MilvusServiceClient milvusClient = new MilvusServiceClient(
ConnectParam.newBuilder()
.withHost("localhost")
.withPort(19530)
.build()
);
Make sure to replace the localhost and 19530 with your Milvus server’s host and port if it runs on a different hostname or port.
Create a Collection
Create a collection with a float vector field:
.withName("book_id")
.withDataType(DataType.Int64)
.withPrimaryKey(true)
.withAutoID(false)
.build();
FieldType fieldType2 = FieldType.newBuilder()
.withName("word_count")
.withDataType(DataType.Int64)
.build();
FieldType fieldType3 = FieldType.newBuilder()
.withName("book_intro")
.withDataType(DataType.FloatVector)
.withDimension(2)
.build();
CreateCollectionParam createCollectionReq = CreateCollectionParam.newBuilder()
.withCollectionName("book")
.withDescription("Test book search")
.withShardsNum(2)
.addFieldType(fieldType1)
.addFieldType(fieldType2)
.addFieldType(fieldType3)
.withEnableDynamicField(true)
.build();
This creates a basic collection with the schema data to store the book information.
Insert the Data
You can then insert some sample vector data as follows:
List<Long> book_id_array = new ArrayList<>();
List<Long> word_count_array = new ArrayList<>();
List<List<Float>> book_intro_array = new ArrayList<>();
for (long i = 0L; i < 2000; ++i) {
book_id_array.add(i);
word_count_array.add(i + 10000);
List<Float> vector = new ArrayList<>();
for (int k = 0; k < 2; ++k) {
vector.add(ran.nextFloat());
}
book_intro_array.add(vector);
}
This uses the Java random features to add a random data.
Conclusion
With the Milvus Java SDK, you can interact with the Milvus vector database using Java. This tutorial covered the basics including connecting to a Milvus server, creating a collection, and inserting the data.