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

     1  // Copyright (C) 2019-2021 Zilliz. All rights reserved.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance
     4  // with the License. You may obtain a copy of the License at
     5  //
     6  // http://www.apache.org/licenses/LICENSE-2.0
     7  //
     8  // Unless required by applicable law or agreed to in writing, software distributed under the License
     9  // is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
    10  // or implied. See the License for the specific language governing permissions and limitations under the License.
    11  
    12  // Package client provides milvus client functions
    13  package client
    14  
    15  import (
    16  	"context"
    17  	"time"
    18  
    19  	"google.golang.org/grpc"
    20  
    21  	"github.com/milvus-io/milvus-proto/go-api/v2/msgpb"
    22  
    23  	"github.com/milvus-io/milvus-sdk-go/v2/entity"
    24  )
    25  
    26  // Client is the interface used to communicate with Milvus
    27  type Client interface {
    28  	// -- client --
    29  	// Close close the remaining connection resources
    30  	Close() error
    31  
    32  	// UsingDatabase for database operation after this function call.
    33  	// All request in any goroutine will be applied to new database on the same client. e.g.
    34  	// 1. goroutine A access DB1.
    35  	// 2. goroutine B call UsingDatabase(ctx, "DB2").
    36  	// 3. goroutine A access DB2 after 2.
    37  	UsingDatabase(ctx context.Context, dbName string) error
    38  
    39  	// -- database --
    40  	// ListDatabases list all database in milvus cluster.
    41  	ListDatabases(ctx context.Context) ([]entity.Database, error)
    42  	// CreateDatabase create database with the given name.
    43  	CreateDatabase(ctx context.Context, dbName string, opts ...CreateDatabaseOption) error
    44  	// DropDatabase drop database with the given db name.
    45  	DropDatabase(ctx context.Context, dbName string, opts ...DropDatabaseOption) error
    46  	// AlterDatabase alter database props with given db name.
    47  	AlterDatabase(ctx context.Context, dbName string, attrs ...entity.DatabaseAttribute) error
    48  	DescribeDatabase(ctx context.Context, dbName string) (*entity.Database, error)
    49  
    50  	// -- collection --
    51  
    52  	// NewCollection intializeds a new collection with pre defined attributes
    53  	NewCollection(ctx context.Context, collName string, dimension int64, opts ...CreateCollectionOption) error
    54  	// ListCollections list collections from connection
    55  	ListCollections(ctx context.Context, opts ...ListCollectionOption) ([]*entity.Collection, error)
    56  	// CreateCollection create collection using provided schema
    57  	CreateCollection(ctx context.Context, schema *entity.Schema, shardsNum int32, opts ...CreateCollectionOption) error
    58  	// DescribeCollection describe collection meta
    59  	DescribeCollection(ctx context.Context, collName string) (*entity.Collection, error)
    60  	// DropCollection drop the specified collection
    61  	DropCollection(ctx context.Context, collName string, opts ...DropCollectionOption) error
    62  	// GetCollectionStatistics get collection statistics
    63  	GetCollectionStatistics(ctx context.Context, collName string) (map[string]string, error)
    64  	// LoadCollection load collection into memory
    65  	LoadCollection(ctx context.Context, collName string, async bool, opts ...LoadCollectionOption) error
    66  	// ReleaseCollection release loaded collection
    67  	ReleaseCollection(ctx context.Context, collName string, opts ...ReleaseCollectionOption) error
    68  	// HasCollection check whether collection exists
    69  	HasCollection(ctx context.Context, collName string) (bool, error)
    70  	// RenameCollection performs renaming for provided collection.
    71  	RenameCollection(ctx context.Context, collName, newName string) error
    72  	// AlterCollection changes collection attributes.
    73  	AlterCollection(ctx context.Context, collName string, attrs ...entity.CollectionAttribute) error
    74  
    75  	// CreateAlias creates an alias for collection
    76  	CreateAlias(ctx context.Context, collName string, alias string) error
    77  	// DropAlias drops the specified Alias
    78  	DropAlias(ctx context.Context, alias string) error
    79  	// AlterAlias changes collection alias to provided alias
    80  	AlterAlias(ctx context.Context, collName string, alias string) error
    81  
    82  	// GetReplicas gets the replica groups as well as their querynodes and shards information
    83  	GetReplicas(ctx context.Context, collName string) ([]*entity.ReplicaGroup, error)
    84  
    85  	// -- authentication --
    86  
    87  	// CreateCredential create new user and password
    88  	CreateCredential(ctx context.Context, username string, password string) error
    89  	// UpdateCredential update password for a user
    90  	UpdateCredential(ctx context.Context, username string, oldPassword string, newPassword string) error
    91  	// DeleteCredential delete a user
    92  	DeleteCredential(ctx context.Context, username string) error
    93  	// ListCredUsers list all usernames
    94  	ListCredUsers(ctx context.Context) ([]string, error)
    95  
    96  	// -- partition --
    97  
    98  	// CreatePartition create partition for collection
    99  	CreatePartition(ctx context.Context, collName string, partitionName string, opts ...CreatePartitionOption) error
   100  	// DropPartition drop partition from collection
   101  	DropPartition(ctx context.Context, collName string, partitionName string, opts ...DropPartitionOption) error
   102  	// ShowPartitions list all partitions from collection
   103  	ShowPartitions(ctx context.Context, collName string) ([]*entity.Partition, error)
   104  	// HasPartition check whether partition exists in collection
   105  	HasPartition(ctx context.Context, collName string, partitionName string) (bool, error)
   106  	// LoadPartitions load partitions into memory
   107  	LoadPartitions(ctx context.Context, collName string, partitionNames []string, async bool, opts ...LoadPartitionsOption) error
   108  	// ReleasePartitions release partitions
   109  	ReleasePartitions(ctx context.Context, collName string, partitionNames []string, opts ...ReleasePartitionsOption) error
   110  
   111  	// -- segment --
   112  	GetPersistentSegmentInfo(ctx context.Context, collName string) ([]*entity.Segment, error)
   113  	// -- index --
   114  
   115  	// CreateIndex create index for field of specified collection
   116  	// currently index naming is not supported, so only one index on vector field is supported
   117  	CreateIndex(ctx context.Context, collName string, fieldName string, idx entity.Index, async bool, opts ...IndexOption) error
   118  	// DescribeIndex describe index on collection
   119  	// currently index naming is not supported, so only one index on vector field is supported
   120  	DescribeIndex(ctx context.Context, collName string, fieldName string, opts ...IndexOption) ([]entity.Index, error)
   121  	// DropIndex drop index from collection with specified field name
   122  	DropIndex(ctx context.Context, collName string, fieldName string, opts ...IndexOption) error
   123  	// GetIndexState get index state with specified collection and field name
   124  	// index naming is not supported yet
   125  	GetIndexState(ctx context.Context, collName string, fieldName string, opts ...IndexOption) (entity.IndexState, error)
   126  	// AlterIndex modifies the index params.
   127  	AlterIndex(ctx context.Context, collName, indexName string, opts ...IndexOption) error
   128  
   129  	// -- basic operation --
   130  
   131  	// Insert column-based data into collection, returns id column values
   132  	Insert(ctx context.Context, collName string, partitionName string, columns ...entity.Column) (entity.Column, error)
   133  	// Flush collection, specified
   134  	Flush(ctx context.Context, collName string, async bool, opts ...FlushOption) error
   135  	// FlushV2 flush collection, specified, return newly sealed segmentIds, all flushed segmentIds of the collection, seal time and error
   136  	// currently it is only used in milvus-backup(https://github.com/zilliztech/milvus-backup)
   137  	FlushV2(ctx context.Context, collName string, async bool, opts ...FlushOption) ([]int64, []int64, int64, map[string]msgpb.MsgPosition, error)
   138  	// DeleteByPks deletes entries related to provided primary keys
   139  	DeleteByPks(ctx context.Context, collName string, partitionName string, ids entity.Column) error
   140  	// Delete deletes entries match expression
   141  	Delete(ctx context.Context, collName string, partitionName string, expr string) error
   142  	// Upsert column-based data of collection, returns id column values
   143  	Upsert(ctx context.Context, collName string, partitionName string, columns ...entity.Column) (entity.Column, error)
   144  	// Search with bool expression
   145  	Search(ctx context.Context, collName string, partitions []string,
   146  		expr string, outputFields []string, vectors []entity.Vector, vectorField string, metricType entity.MetricType, topK int, sp entity.SearchParam, opts ...SearchQueryOptionFunc) ([]SearchResult, error)
   147  	// QueryByPks query record by specified primary key(s).
   148  	QueryByPks(ctx context.Context, collectionName string, partitionNames []string, ids entity.Column, outputFields []string, opts ...SearchQueryOptionFunc) (ResultSet, error)
   149  	// Query performs query records with boolean expression.
   150  	Query(ctx context.Context, collectionName string, partitionNames []string, expr string, outputFields []string, opts ...SearchQueryOptionFunc) (ResultSet, error)
   151  	// Get grabs the inserted entities using the primary key from the Collection.
   152  	Get(ctx context.Context, collectionName string, ids entity.Column, opts ...GetOption) (ResultSet, error)
   153  	// QueryIterator returns data matches provided criterion in iterator mode.
   154  	QueryIterator(ctx context.Context, opt *QueryIteratorOption) (*QueryIterator, error)
   155  
   156  	// CalcDistance calculate the distance between vectors specified by ids or provided
   157  	CalcDistance(ctx context.Context, collName string, partitions []string,
   158  		metricType entity.MetricType, opLeft, opRight entity.Column) (entity.Column, error)
   159  
   160  	// -- row based apis --
   161  
   162  	// CreateCollectionByRow create collection by row
   163  	CreateCollectionByRow(ctx context.Context, row entity.Row, shardNum int32) error
   164  	// DEPRECATED
   165  	// InsertByRows insert by rows
   166  	InsertByRows(ctx context.Context, collName string, paritionName string, rows []entity.Row) (entity.Column, error)
   167  	// InsertRows insert with row base data.
   168  	InsertRows(ctx context.Context, collName string, partitionName string, rows []interface{}) (entity.Column, error)
   169  
   170  	// ManualCompaction triggers a compaction on provided collection
   171  	ManualCompaction(ctx context.Context, collName string, toleranceDuration time.Duration) (int64, error)
   172  	// GetCompactionState get compaction state of provided compaction id
   173  	GetCompactionState(ctx context.Context, id int64) (entity.CompactionState, error)
   174  	// GetCompactionStateWithPlans get compaction state with plans of provided compaction id
   175  	GetCompactionStateWithPlans(ctx context.Context, id int64) (entity.CompactionState, []entity.CompactionPlan, error)
   176  
   177  	// BulkInsert import data files(json, numpy, etc.) on MinIO/S3 storage, read and parse them into sealed segments
   178  	BulkInsert(ctx context.Context, collName string, partitionName string, files []string, opts ...BulkInsertOption) (int64, error)
   179  	// GetBulkInsertState checks import task state
   180  	GetBulkInsertState(ctx context.Context, taskID int64) (*entity.BulkInsertTaskState, error)
   181  	// ListBulkInsertTasks list state of all import tasks
   182  	ListBulkInsertTasks(ctx context.Context, collName string, limit int64) ([]*entity.BulkInsertTaskState, error)
   183  
   184  	// CreateRole creates a role entity in Milvus.
   185  	CreateRole(ctx context.Context, name string) error
   186  	// DropRole drops a role entity in Milvus.
   187  	DropRole(ctx context.Context, name string) error
   188  	// AddUserRole adds one role for user.
   189  	AddUserRole(ctx context.Context, username string, role string) error
   190  	// RemoveUserRole removes one role from user.
   191  	RemoveUserRole(ctx context.Context, username string, role string) error
   192  	// ListRoles lists the role objects in system.
   193  	ListRoles(ctx context.Context) ([]entity.Role, error)
   194  	// ListUsers lists the user objects in system.
   195  	ListUsers(ctx context.Context) ([]entity.User, error)
   196  	// DescribeUser describes specific user attributes in the system
   197  	DescribeUser(ctx context.Context, username string) (entity.UserDescription, error)
   198  	// DescribeUsers describe all users attributes in the system
   199  	DescribeUsers(ctx context.Context) ([]entity.UserDescription, error)
   200  	// ListGrant lists a grant info for the role and the specific object
   201  	ListGrant(ctx context.Context, role string, object string, objectName string, dbName string) ([]entity.RoleGrants, error)
   202  	// ListGrants lists all assigned privileges and objects for the role.
   203  	ListGrants(ctx context.Context, role string, dbName string) ([]entity.RoleGrants, error)
   204  	// Grant adds privilege for role.
   205  	Grant(ctx context.Context, role string, objectType entity.PriviledgeObjectType, object string) error
   206  	// Revoke removes privilege from role.
   207  	Revoke(ctx context.Context, role string, objectType entity.PriviledgeObjectType, object string) error
   208  
   209  	// GetLoadingProgress get the collection or partitions loading progress
   210  	GetLoadingProgress(ctx context.Context, collectionName string, partitionNames []string) (int64, error)
   211  	// GetLoadState get the collection or partitions load state
   212  	GetLoadState(ctx context.Context, collectionName string, partitionNames []string) (entity.LoadState, error)
   213  
   214  	// ListResourceGroups returns list of resource group names in current Milvus instance.
   215  	ListResourceGroups(ctx context.Context) ([]string, error)
   216  	// CreateResourceGroup creates a resource group with provided name.
   217  	CreateResourceGroup(ctx context.Context, rgName string) error
   218  	// DescribeResourceGroup returns resource groups information.
   219  	DescribeResourceGroup(ctx context.Context, rgName string) (*entity.ResourceGroup, error)
   220  	// DropResourceGroup drops the resource group with provided name.
   221  	DropResourceGroup(ctx context.Context, rgName string) error
   222  	// TransferNode transfers querynodes between resource groups.
   223  	TransferNode(ctx context.Context, sourceRg, targetRg string, nodesNum int32) error
   224  	// TransferReplica transfer collection replicas between source,target resource group.
   225  	TransferReplica(ctx context.Context, sourceRg, targetRg string, collectionName string, replicaNum int64) error
   226  
   227  	// GetVersion get milvus version
   228  	GetVersion(ctx context.Context) (string, error)
   229  	// CheckHealth returns milvus state
   230  	CheckHealth(ctx context.Context) (*entity.MilvusState, error)
   231  
   232  	ReplicateMessage(ctx context.Context,
   233  		channelName string, beginTs, endTs uint64,
   234  		msgsBytes [][]byte, startPositions, endPositions []*msgpb.MsgPosition,
   235  		opts ...ReplicateMessageOption,
   236  	) (*entity.MessageInfo, error)
   237  
   238  	HybridSearch(ctx context.Context, collName string, partitions []string, limit int, outputFields []string, reranker Reranker, subRequests []*ANNSearchRequest, opts ...SearchQueryOptionFunc) ([]SearchResult, error)
   239  }
   240  
   241  // NewClient create a client connected to remote milvus cluster.
   242  // More connect option can be modified by Config.
   243  func NewClient(ctx context.Context, config Config) (Client, error) {
   244  	if err := config.parse(); err != nil {
   245  		return nil, err
   246  	}
   247  
   248  	c := &GrpcClient{
   249  		config: &config,
   250  	}
   251  
   252  	// Parse remote address.
   253  	addr := c.config.getParsedAddress()
   254  
   255  	// Parse grpc options
   256  	options := c.config.getDialOption()
   257  
   258  	// Connect the grpc server.
   259  	if err := c.connect(ctx, addr, options...); err != nil {
   260  		return nil, err
   261  	}
   262  
   263  	return c, nil
   264  }
   265  
   266  // NewGrpcClient create client with grpc addr
   267  // the `Connect` API will be called for you
   268  // dialOptions contains the dial option(s) that control the grpc dialing process
   269  // !!!Deprecated in future, use `NewClient` first.
   270  func NewGrpcClient(ctx context.Context, addr string, dialOptions ...grpc.DialOption) (Client, error) {
   271  	return NewClient(ctx, Config{
   272  		Address:     addr,
   273  		DialOptions: dialOptions,
   274  	})
   275  }
   276  
   277  // NewDefaultGrpcClient creates a new gRPC client.
   278  // !!!Deprecated in future, use `NewClient` first.
   279  func NewDefaultGrpcClient(ctx context.Context, addr string) (Client, error) {
   280  	return NewClient(
   281  		ctx, Config{
   282  			Address: addr,
   283  		},
   284  	)
   285  }
   286  
   287  // NewDefaultGrpcClientWithURI creates a new gRPC client with URI.
   288  // !!!Deprecated in future, use `NewClient` first.
   289  func NewDefaultGrpcClientWithURI(ctx context.Context, uri, username, password string) (Client, error) {
   290  	return NewClient(ctx, Config{
   291  		Address:  uri,
   292  		Username: username,
   293  		Password: password,
   294  	})
   295  }
   296  
   297  // NewDefaultGrpcClientWithTLSAuth creates a new gRPC client with TLS authentication.
   298  // !!!Deprecated in future, use `NewClient` first.
   299  func NewDefaultGrpcClientWithTLSAuth(ctx context.Context, addr, username, password string) (Client, error) {
   300  	return NewClient(
   301  		ctx,
   302  		Config{
   303  			Address:       addr,
   304  			Username:      username,
   305  			Password:      password,
   306  			EnableTLSAuth: true,
   307  		},
   308  	)
   309  }
   310  
   311  // NewDefaultGrpcClientWithAuth creates a new gRPC client with authentication.
   312  // !!!Deprecated in future, use `NewClient` first.
   313  func NewDefaultGrpcClientWithAuth(ctx context.Context, addr, username, password string) (Client, error) {
   314  	return NewClient(
   315  		ctx,
   316  		Config{
   317  			Address:  addr,
   318  			Username: username,
   319  			Password: password,
   320  		},
   321  	)
   322  }