| by Arround The Web | No comments

Connect to Milvus Using Golang

Milvus is an open-source vector database that manages both vectors and traditional scalar data at scale. It allows us to conduct similarity searches and analytics on high-dimensional data.

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:

go get -u github.com/milvus-io/milvus-sdk-go/v2

Import Milvus-Sdk-Go

Next, in your go source code, add the following line to import the SDK into your project:

import "github.com/milvus-io/milvus-sdk-go/v2/client"

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.

milvusAddr := `localhost:19530`

Connect to Milvus Server

Finally, we can create a client to the server and initialize the connection as shown in the following code:

ctx := context.Background()

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:

  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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.

Share Button

Source: linuxhint.com

Leave a Reply