In this tutorial, we will learn how to connect to a Milvus server using the milvus-sdk-go, the Go SDK for Milvus.
Please note that this tutorial assumes that you already have a running Milvus server. You can follow our tutorial to learn how to configure your system’s Milvus server.
Prerequisites:
- A running Milvus server
- Installed Golang Compiler on your machine
- Basic knowledge of the Go programming language
Install Milvus-Sdk-Go
Before we can write any code, we need to install milvus-sdk-go in the Go workspace. We can do this by running the following command:
Import Milvus-Sdk-Go
Next, in your go source code, add the following line to import the SDK into your project:
Create a Client Instance
We need to create a client instance to connect to the Milvus server. To do this, define the address to the Milvus server first.
Connect to Milvus Server
Finally, we can create a client to the server and initialize the connection as shown in the following code:
ctx, cancel := context.WithTimeout(ctx, 2*time.Second)
defer cancel()
c, err := client.NewClient(ctx, client.Config{
Address: milvusAddr,
})
if err != nil {
// handling error and exit, to make example simple here
log.Fatal("failed to connect to milvus:", err.Error())
Let us break down the given code step by step:
- ctx := context.Background() – This line creates a new context to manage a network request’s lifecycle. The context carries deadlines, cancelation signals, and other request-scoped values across API boundaries and between processes.
- ctx, cancel := context.WithTimeout(ctx, 2*time.Second) – In this block, we create a new context with a timeout of two seconds. The request is terminated if a response is not received within two seconds.
- defer cancel() – The “defer” keyword ensures that the cancel function is called when the surrounding function returns, which means that the context is closed to avoid leaks.
- c, err := client.NewClient(ctx, client.Config{ Address: milvusAddr, }) – In this block, we create a new Milvus client and connect to the server using the specified milvusAddr address.
- if err != nil { log.Fatal(“failed to connect to milvus:”, err.Error()) } – Finally, we use this block to exit the program if an error is encountered during the creation of the client.
Conclusion
This tutorial taught us how to connect to a Milvus server using milvus-sdk-go. Following these steps allows you to take advantage of the powerful capabilities of Milvus.