github.com/milvus-io/milvus-sdk-go/v2@v2.4.1/examples/iterator/main.go (about)

     1  package main
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"io"
     7  	"log"
     8  	"math/rand"
     9  
    10  	"github.com/milvus-io/milvus-sdk-go/v2/client"
    11  	"github.com/milvus-io/milvus-sdk-go/v2/entity"
    12  )
    13  
    14  const (
    15  	milvusAddr     = `localhost:19530`
    16  	nEntities, dim = 3000, 128
    17  	collectionName = "hello_iterator"
    18  
    19  	msgFmt                         = "==== %s ====\n"
    20  	idCol, randomCol, embeddingCol = "ID", "random", "embeddings"
    21  	topK                           = 3
    22  )
    23  
    24  func main() {
    25  	ctx := context.Background()
    26  
    27  	log.Printf(msgFmt, "start connecting to Milvus")
    28  	c, err := client.NewClient(ctx, client.Config{
    29  		Address: milvusAddr,
    30  	})
    31  	if err != nil {
    32  		log.Fatal("failed to connect to milvus, err: ", err.Error())
    33  	}
    34  	defer c.Close()
    35  
    36  	// delete collection if exists
    37  	has, err := c.HasCollection(ctx, collectionName)
    38  	if err != nil {
    39  		log.Fatalf("failed to check collection exists, err: %v", err)
    40  	}
    41  	if has {
    42  		c.DropCollection(ctx, collectionName)
    43  	}
    44  
    45  	// create collection
    46  	log.Printf(msgFmt, fmt.Sprintf("create collection, `%s`", collectionName))
    47  	schema := entity.NewSchema().WithName(collectionName).WithDescription("hello_milvus is the simplest demo to introduce the APIs").
    48  		WithField(entity.NewField().WithName(idCol).WithDataType(entity.FieldTypeInt64).WithIsPrimaryKey(true).WithIsAutoID(false)).
    49  		WithField(entity.NewField().WithName(randomCol).WithDataType(entity.FieldTypeDouble)).
    50  		WithField(entity.NewField().WithName(embeddingCol).WithDataType(entity.FieldTypeFloatVector).WithDim(dim))
    51  
    52  	if err := c.CreateCollection(ctx, schema, entity.DefaultShardNumber); err != nil { // use default shard number
    53  		log.Fatalf("create collection failed, err: %v", err)
    54  	}
    55  
    56  	// build index
    57  	log.Printf(msgFmt, "start creating index IVF_FLAT")
    58  	idx, err := entity.NewIndexIvfFlat(entity.L2, 128)
    59  	if err != nil {
    60  		log.Fatalf("failed to create ivf flat index, err: %v", err)
    61  	}
    62  	if err := c.CreateIndex(ctx, collectionName, embeddingCol, idx, false); err != nil {
    63  		log.Fatalf("failed to create index, err: %v", err)
    64  	}
    65  
    66  	log.Printf(msgFmt, "start loading collection")
    67  	err = c.LoadCollection(ctx, collectionName, false)
    68  	if err != nil {
    69  		log.Fatalf("failed to load collection, err: %v", err)
    70  	}
    71  
    72  	// insert data
    73  	log.Printf(msgFmt, "start inserting random entities")
    74  	idList, randomList := make([]int64, 0, nEntities), make([]float64, 0, nEntities)
    75  	embeddingList := make([][]float32, 0, nEntities)
    76  
    77  	// generate data
    78  	for i := 0; i < nEntities; i++ {
    79  		idList = append(idList, int64(i))
    80  	}
    81  	for i := 0; i < nEntities; i++ {
    82  		randomList = append(randomList, rand.Float64())
    83  	}
    84  	for i := 0; i < nEntities; i++ {
    85  		vec := make([]float32, 0, dim)
    86  		for j := 0; j < dim; j++ {
    87  			vec = append(vec, rand.Float32())
    88  		}
    89  		embeddingList = append(embeddingList, vec)
    90  	}
    91  	idColData := entity.NewColumnInt64(idCol, idList)
    92  	randomColData := entity.NewColumnDouble(randomCol, randomList)
    93  	embeddingColData := entity.NewColumnFloatVector(embeddingCol, dim, embeddingList)
    94  
    95  	if _, err := c.Insert(ctx, collectionName, "", idColData, randomColData, embeddingColData); err != nil {
    96  		log.Fatalf("failed to insert random data into `hello_milvus, err: %v", err)
    97  	}
    98  
    99  	if err := c.Flush(ctx, collectionName, false); err != nil {
   100  		log.Fatalf("failed to flush data, err: %v", err)
   101  	}
   102  
   103  	itr, err := c.QueryIterator(ctx, client.NewQueryIteratorOption(collectionName).WithOutputFields(idCol).WithBatchSize(100))
   104  	if err != nil {
   105  		log.Fatal("failed to query iterator: ", err.Error())
   106  	}
   107  	for {
   108  		rs, err := itr.Next(ctx)
   109  		if err != nil {
   110  			if err == io.EOF {
   111  				log.Println("iterator reach EOF")
   112  				break
   113  			}
   114  			log.Fatal("failed to query iterator. next: ", err.Error())
   115  		}
   116  		var idlist []int64
   117  		for _, col := range rs {
   118  			if col.Name() == idCol {
   119  				idColumn := col.(*entity.ColumnInt64)
   120  				for i := 0; i < col.Len(); i++ {
   121  					val, err := idColumn.ValueByIdx(i)
   122  					if err != nil {
   123  						log.Fatal(err)
   124  					}
   125  					idlist = append(idlist, val)
   126  				}
   127  			}
   128  		}
   129  		log.Printf("\tids: %#v\n", idlist)
   130  	}
   131  
   132  	// drop collection
   133  	log.Printf(msgFmt, "drop collection `hello_milvus`")
   134  	if err := c.DropCollection(ctx, collectionName); err != nil {
   135  		log.Fatalf("failed to drop collection, err: %v", err)
   136  	}
   137  }