Package: dashvector
DashVector Client Python LibraryDashVector is a scalable and fully-managed vector-database service for building various machine learning applications. The DashVector client SDK is your gateway to access the DashVector service.For more information about DashVector, please visit:https://help.aliyun.com/document_detail/2510225.htmlInstallationTo install the DashVector client Python SDK, simply run:pipinstalldashvectorQuickStartimportnumpyasnpimportdashvector# Use DashVector `Client` api to communicate with the backend vectorDB service.client=dashvector.Client(api_key='YOUR-DASHVECTOR-API-KEY')# Create a collection named "quickstart" with dimension of 4, using the default Cosine distance metricrsp=client.create(name='quickstart',dimension=4)assertrsp# Get a collection by namecollection=client.get(name='quickstart')# Operations on 'Collection' includes Inert/Query/Upsert/Update/Delete/Fetch of docs# Here we insert sample data (4-dimensional vectors) in batches of 16collection.insert([dashvector.Doc(id=str(i),vector=np.random.rand(4),fields={'anykey':'anyvalue'})foriinrange(16)])# Query a vector from the collectiondocs=collection.query([0.1,0.2,0.3,0.4],topk=5)print(docs)# Get statistics about collectionstats=collection.stats()print(stats)# Delete a collection by nameclient.delete(name='quickstart')ReferenceCreate a ClientClienthost various APIs for interacting with DashVectorCollection.dashvector.Client(api_key:str,endpoint:str='dashvector.cn-hangzhou.aliyuncs.com',protocal:dashvector.DashVectorProtocol=dashvector.DashVectorProtocol.GRPC,timeout:float=10.0)->ClientParametersTypeRequiredDescriptionapi_keystrYesYour DashVector API-KEYendpointstrNoService Endpoint.Default value:dashvector.cn-hangzhou.aliyuncs.comprotocolDashVectorProtocolNoCommunication protocol, support HTTP and GRPC.Default value:DashVectorProtocol.GRPCtimeoutfloatNoTimeout period (in seconds), -1 means no timeout.Default value:10.0Example:importdashvectorclient=dashvector.Client(api_key='YOUR-DASHVECTOR-API-KEY')assertclientCreate CollectionClient.create(name:str,dimension:int,dtype:Union[Type[int],Type[float]]=float,fields_schema:Optional[Dict[str,Union[Type[str],Type[int],Type[float],Type[bool]]]]=None,metric:str='cosine',timeout:Optional[int]=None)->DashVectorResponseParametersTypeRequiredDescriptionnamestrYesThe name of the Collection to create.dimensionintYesThe dimensions of the Collection's vectors. Valid values:  1-20,000dtypeUnion[Type[int], Type[float]]NoThe date type of the Collection's vectors.Default value:Type[float]fields_schemaOptional[Dict[str, Union[Type[str], Type[int], Type[float], Type[bool]]]]NoFields schema of the Collection.Default value:Nonee.g.{"name": str, "age": int}metricstrNoVector similarity metric. Forcosine, dtype must befloat.Valid values:1. (Default)cosine2.dotproduct3.euclideantimeoutOptional[int]NoTimeout period (in seconds), -1 means asynchronous creation collection.Default value:NoneExample:importdashvectorclient=dashvector.Client(api_key='YOUR-DASHVECTOR-API-KEY')rsp=client.create('YOUR-COLLECTION-NAME',dimension=4)assertrspList CollectionsClient.list() -> DashVectorResponseExample:importdashvectorclient=dashvector.Client(api_key='YOUR-DASHVECTOR-API-KEY')collections=client.list()forcollectionincollections:print(collection)# outputs:# 'quickstart'Describe CollectionClient.describe(name: str) -> DashVectorResponseParametersTypeRequiredDescriptionnamestrYesThe name of the Collection to describe.Example:importdashvectorclient=dashvector.Client(api_key='YOUR-DASHVECTOR-API-KEY')rsp=client.describe('YOUR-COLLECTION-NAME')print(rsp)# example output:# {#   "request_id": "8d3ac14e-5382-4736-b77c-4318761ddfab",#   "code": 0,#   "message": "",#   "output": {#     "name": "quickstart",#     "dimension": 4,#     "dtype": "FLOAT",#     "metric": "dotproduct",#     "fields_schema": {#       "name": "STRING",#       "age": "INT",#       "height": "FLOAT"#     },#     "status": "SERVING",#     "partitions": {#       "default": "SERVING"#     }#   }# }Delete CollectionClient.delete(name: str) -> DashVectorResponseParametersTypeRequiredDescriptionnamestrYesThe name of the Collection to delete.Example:importdashvectorclient=dashvector.Client(api_key='YOUR-DASHVECTOR-API-KEY')client.delete('YOUR-COLLECTION-NAME')Get a Collection InstanceCollectionprovides APIs for accessingDocandPartitionClient.get(name: str) -> CollectionParametersTypeRequiredDescriptionnamestrYesThe name of the Collection to get.Example:importdashvectorclient=dashvector.Client(api_key='YOUR-DASHVECTOR-API-KEY')collection=client.get('YOUR-COLLECTION-NAME')assertcollectionDescribe Collection StatisticsCollection.stats() -> DashVectorResponseExample:importdashvectorclient=dashvector.Client(api_key='YOUR-DASHVECTOR-API-KEY')collection=client.get('YOUR-COLLECTION-NAME')rsp=collection.stats()print(rsp)# example output:# {#   "request_id": "14448bcb-c9a3-49a8-9152-0de3990bce59",#   "code": 0,#   "message": "Success",#   "output": {#     "total_doc_count": "26",#     "index_completeness": 1.0,#     "partitions": {#       "default": {#         "total_doc_count": "26"#       }#     }#   }# }Insert/Update/Upsert DocsCollection.insert(docs:Union[Doc,List[Doc],Tuple,List[Tuple]],partition:Optional[str]=None,async_req:False)->DashVectorResponseParametersTypeRequiredDescriptiondocsUnion[Doc, List[Doc], Tuple, List[Tuple]]YesThe docs to Insert/Update/Upsert.partitionOptional[str]NoName of the partition to Insert/Update/Upsert.Default value:Noneasync_reqboolNoEnable async request or not.Default value:FalseExample:importdashvectorimportnumpyasnpclient=dashvector.Client(api_key='YOUR-DASHVECTOR-API-KEY')collection=client.get('YOUR-COLLECTION-NAME')# insert a doc with Tuplecollection.insert(('YOUR-DOC-ID1',[0.1,0.2,0.3,0.4]))collection.insert(('YOUR-DOC-ID2',[0.2,0.3,0.4,0.5],{'age':30,'name':'alice','anykey':'anyvalue'}))# insert a doc with dashvector.Doccollection.insert(dashvector.Doc(id='YOUR-DOC-ID3',vector=[0.3,0.4,0.5,0.6],fields={'foo':'bar'}))# insert in batchesret=collection.insert([('YOUR-DOC-ID4',[0.2,0.7,0.8,1.3],{'age':1}),('YOUR-DOC-ID4',[0.3,0.6,0.9,1.2],{'age':2}),('YOUR-DOC-ID6',[0.4,0.5,1.0,1.1],{'age':3})])# insert in batchesret=collection.insert([dashvector.Doc(id=str(i),vector=np.random.rand(4))foriinrange(10)])# async insertret_funture=collection.insert([dashvector.Doc(id=str(i+10),vector=np.random.rand(4))foriinrange(10)],async_req=True)ret=ret_funture.get()Query a CollectionCollection.query(vector:Optional[Union[List[Union[int,float]],np.ndarray]]=None,id:Optional[str]=None,topk:int=10,filter:Optional[str]=None,include_vector:bool=False,partition:Optional[str]=None,output_fields:Optional[List[str]]=None,async_req:False)->DashVectorResponseParametersTypeRequiredDescriptionvectorOptional[Union[List[Union[int, float]], np.ndarray]]NoThe vector to queryidOptional[str]NoThe doc id to query.Settingidmeans searching by vector corresponding to the idtopkOptional[str]NoNumber of similarity results to return.Default value:10filterOptional[str]NoExpression used to filter resultsDefault value: Nonee.g.age>20include_vectorboolNoReturn vector details or not.Default value:FalsepartitionOptional[str]NoName of the partition to Query.Default value:Noneoutput_fieldsOptional[List[str]]NoList of field names to return.Default value:None, means return all fieldse.g.['name', 'age']async_reqboolNoEnable async request or not.Default value:FalseExample:importdashvectorclient=dashvector.Client(api_key='YOUR-DASHVECTOR-API-KEY')collection=client.get('YOUR-COLLECTION-NAME')match_docs=collection.query([0.1,0.2,0.3,0.4],topk=100,filter='age>20',include_vector=True,output_fields=['age','name','foo'])ifmatch_docs:fordocinmatch_docs:print(doc.id)print(doc.vector)print(doc.fields)print(doc.score)Delete Docscollection.delete(ids:Union[str,List[str]],delete_all:bool=False,partition:Optional[str]=None,async_req:bool=False)->DashVectorResponseParametersTypeRequiredDescriptionidsUnion[str, List[str]]YesThe id (or list of ids) for the Doc(s) to Deletedelete_allboolNoDelete all vectors from partition.Default value:FalsepartitionOptional[str]NoName of the partition to Delete from.Default value:Noneasync_reqboolNoEnable async request or not.Default value:FalseExample:importdashvectorclient=dashvector.Client(api_key='YOUR-DASHVECTOR-API-KEY')collection=client.get('YOUR-COLLECTION-NAME')collection.delete(['YOUR-DOC-ID1','YOUR-DOC-ID2'])Fetch DocsCollection.fetch(ids:Union[str,List[str]],partition:Optional[str]=None,async_req:bool=False)->DashVectorResponseParametersTypeRequiredDescriptionidsUnion[str, List[str]]YesThe id (or list of ids) for the Doc(s) to FetchpartitionOptional[str]NoName of the partition to Fetch from.Default value:Noneasync_reqboolNoEnable async request or not.Default value:FalseExample:importdashvectorclient=dashvector.Client(api_key='YOUR-DASHVECTOR-API-KEY')collection=client.get('YOUR-COLLECTION-NAME')fetch_docs=collection.fetch(['YOUR-DOC-ID1','YOUR-DOC-ID2'])iffetch_docs:fordoc_idinfetch_docs:doc=fetch_docs[doc_id]print(doc.id)print(doc.vector)print(doc.fields)Create Collection PartitionCollection.create_partition(name: str) -> DashVectorResponseParametersTypeRequiredDescriptionnamestrYesThe name of the Partition to Create.timeoutOptional[int]NoTimeout period (in seconds), -1 means asynchronous creation partition.Default value:NoneExample:importdashvectorclient=dashvector.Client(api_key='YOUR-DASHVECTOR-API-KEY')collection=client.get('YOUR-COLLECTION-NAME')rsp=collection.create_partition('YOUR-PARTITION-NAME')assertrspDelete Collection PartitionCollection.delete_partition(name: str) -> DashVectorResponseParametersTypeRequiredDescriptionnamestrYesThe name of the Partition to Delete.Example:importdashvectorclient=dashvector.Client(api_key='YOUR-DASHVECTOR-API-KEY')collection=client.get('YOUR-COLLECTION-NAME')rsp=collection.delete_partition('YOUR-PARTITION-NAME')assertrspList Collection PartitionsCollection.list_partitions() -> DashVectorResponseExample:importdashvectorclient=dashvector.Client(api_key='YOUR-DASHVECTOR-API-KEY')collection=client.get('YOUR-COLLECTION-NAME')partitions=collection.list_partitions()assertpartitionsforptinpartitions:print(pt)Describe Collection PartitionCollection.describe_partition(name: str) -> DashVectorResponseParametersTypeRequiredDescriptionnamestrYesThe name of the Partition to Describe.Example:importdashvectorclient=dashvector.Client(api_key='YOUR-DASHVECTOR-API-KEY')collection=client.get('YOUR-COLLECTION-NAME')rsp=collection.describe_partition('shoes')print(rsp)# example output:# {"request_id":"296267a7-68e2-483a-87e6-5992d85a5806","code":0,"message":"","output":"SERVING"}Statistics for Collection PartitionCollection.stats_partition(name: str) -> DashVectorResponseParametersTypeRequiredDescriptionnamestrYesThe name of the Partition to get Statistics.Example:importdashvectorclient=dashvector.Client(api_key='YOUR-DASHVECTOR-API-KEY')collection=client.get('YOUR-COLLECTION-NAME')rsp=collection.stats_partition('shoes')print(rsp)# example outptut:# {#     "code":0,#     "message":"",#     "requests_id":"330a2bcb-e4a7-4fc6-a711-2fe5f8a24e8c",#     "output":{#         "total_doc_count":0#     }# }Classdashvector.Doc@dataclass(frozen=True)classDoc(object):id:strvector:Union[List[int],List[float],numpy.ndarray]fields:Optional[Dict[str,Union[Type[str],Type[int],Type[float],Type[bool]]]]=Nonescore:float=0.0dashvector.DashVectorResponseclassDashVectorResponse(object):code:DashVectorCodemessage:strrequest_id:stroutput:AnyLicenseThis project is licensed under the Apache License (Version 2.0).