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

     1  package main
     2  
     3  import (
     4  	"context"
     5  	"encoding/binary"
     6  	"fmt"
     7  	"log"
     8  	"math/rand"
     9  	"time"
    10  	"unsafe"
    11  
    12  	"github.com/milvus-io/milvus-sdk-go/v2/client"
    13  	"github.com/milvus-io/milvus-sdk-go/v2/entity"
    14  )
    15  
    16  const (
    17  	milvusAddr     = `localhost:19530`
    18  	nEntities, dim = 3000, 128
    19  	collectionName = "query_example"
    20  
    21  	msgFmt                         = "==== %s ====\n"
    22  	idCol, randomCol, embeddingCol = "ID", "random", "embeddings"
    23  )
    24  
    25  func toBFloat16(f float32) []byte {
    26  	bs := make([]byte, 2)
    27  	u32 := *(*uint32)(unsafe.Pointer(&f))
    28  	binary.LittleEndian.PutUint16(bs, uint16(u32>>16))
    29  	return bs
    30  }
    31  
    32  func main() {
    33  	ctx := context.Background()
    34  
    35  	log.Printf(msgFmt, "start connecting to Milvus")
    36  	c, err := client.NewClient(ctx, client.Config{
    37  		Address: milvusAddr,
    38  	})
    39  	if err != nil {
    40  		log.Fatalf("failed to connect to milvus, err: %v", err)
    41  	}
    42  	defer c.Close()
    43  
    44  	// delete collection if exists
    45  	has, err := c.HasCollection(ctx, collectionName)
    46  	if err != nil {
    47  		log.Fatalf("failed to check collection exists, err: %v", err)
    48  	}
    49  	if has {
    50  		c.DropCollection(ctx, collectionName)
    51  	}
    52  
    53  	// define schema
    54  	log.Printf(msgFmt, fmt.Sprintf("create collection, `%s`", collectionName))
    55  	schema := entity.NewSchema().WithName(collectionName).
    56  		WithField(entity.NewField().WithName(idCol).WithDataType(entity.FieldTypeInt64).WithIsPrimaryKey(true).WithIsAutoID(false)).
    57  		WithField(entity.NewField().WithName(randomCol).WithDataType(entity.FieldTypeDouble)).
    58  		WithField(entity.NewField().WithName(embeddingCol).WithDataType(entity.FieldTypeBFloat16Vector).WithDim(dim))
    59  
    60  	// create collection with consistency level, which serves as the default search/query consistency level
    61  	if err := c.CreateCollection(ctx, schema, entity.DefaultShardNumber, client.WithConsistencyLevel(entity.ClBounded)); err != nil {
    62  		log.Fatalf("create collection failed, err: %v", err)
    63  	}
    64  
    65  	log.Printf(msgFmt, "start inserting random entities")
    66  	idList, randomList := make([]int64, 0, nEntities), make([]float64, 0, nEntities)
    67  	embeddingList := make([][]byte, 0, nEntities)
    68  
    69  	rand.Seed(time.Now().UnixNano())
    70  
    71  	// generate data
    72  	for i := 0; i < nEntities; i++ {
    73  		idList = append(idList, int64(i))
    74  	}
    75  	for i := 0; i < nEntities; i++ {
    76  		randomList = append(randomList, rand.Float64())
    77  	}
    78  	for i := 0; i < nEntities; i++ {
    79  		vec := make([]byte, 0, dim*2)
    80  		for j := 0; j < dim; j++ {
    81  			vec = append(vec, toBFloat16(rand.Float32())...)
    82  		}
    83  		embeddingList = append(embeddingList, vec)
    84  	}
    85  	idColData := entity.NewColumnInt64(idCol, idList)
    86  	randomColData := entity.NewColumnDouble(randomCol, randomList)
    87  	embeddingColData := entity.NewColumnBFloat16Vector(embeddingCol, dim, embeddingList)
    88  
    89  	// build index
    90  	log.Printf(msgFmt, "start creating index IVF_FLAT")
    91  	idx, err := entity.NewIndexIvfFlat(entity.L2, 128)
    92  	if err != nil {
    93  		log.Fatalf("failed to create ivf flat index, err: %v", err)
    94  	}
    95  	if err := c.CreateIndex(ctx, collectionName, embeddingCol, idx, false); err != nil {
    96  		log.Fatalf("failed to create index, err: %v", err)
    97  	}
    98  
    99  	// insert data
   100  	if _, err := c.Insert(ctx, collectionName, "", idColData, randomColData, embeddingColData); err != nil {
   101  		log.Fatalf("failed to insert random data into %s, err: %s", collectionName, err.Error())
   102  	}
   103  
   104  	log.Printf(msgFmt, "start loading collection")
   105  	err = c.LoadCollection(ctx, collectionName, false)
   106  	if err != nil {
   107  		log.Fatalf("failed to load collection, err: %v", err)
   108  	}
   109  
   110  	//query
   111  	expr := "ID in [0, 1, 2]"
   112  	log.Printf(msgFmt, fmt.Sprintf("query with expr `%s`", expr))
   113  	resultSet, err := c.Query(ctx, collectionName, nil, expr, []string{idCol, randomCol})
   114  	if err != nil {
   115  		log.Fatalf("failed to query result, err: %v", err)
   116  	}
   117  	printResultSet(resultSet, idCol, randomCol)
   118  
   119  	// drop collection
   120  	log.Printf(msgFmt, fmt.Sprintf("drop collection `%s`", collectionName))
   121  	if err := c.DropCollection(ctx, collectionName); err != nil {
   122  		log.Fatalf("failed to drop collection, err: %v", err)
   123  	}
   124  }
   125  
   126  func printResultSet(rs client.ResultSet, outputFields ...string) {
   127  	for _, fieldName := range outputFields {
   128  		column := rs.GetColumn(fieldName)
   129  		if column == nil {
   130  			log.Printf("column %s not exists in result set\n", fieldName)
   131  		}
   132  		switch column.Type() {
   133  		case entity.FieldTypeInt64:
   134  			var result []int64
   135  			for i := 0; i < column.Len(); i++ {
   136  				v, err := column.GetAsInt64(i)
   137  				if err != nil {
   138  					log.Printf("column %s row %d cannot GetAsInt64, %s\n", fieldName, i, err.Error())
   139  				}
   140  				result = append(result, v)
   141  			}
   142  			log.Printf("Column %s: value: %v\n", fieldName, result)
   143  		case entity.FieldTypeDouble:
   144  			var result []float64
   145  			for i := 0; i < column.Len(); i++ {
   146  				v, err := column.GetAsDouble(i)
   147  				if err != nil {
   148  					log.Printf("column %s row %d cannot GetAsDouble, %s\n", fieldName, i, err.Error())
   149  				}
   150  				result = append(result, v)
   151  			}
   152  			log.Printf("Column %s: value: %v\n", fieldName, result)
   153  		}
   154  	}
   155  }