This topic describes how to use tOSS SDK for Python 2.0 to call the QueryVectors operation and perform a similarity search in a vector index.
Permissions
An Alibaba Cloud account has all permissions by default. A Resource Access Management (RAM) user or RAM role under an Alibaba Cloud account has no permissions by default. The Alibaba Cloud account or an administrator must grant permissions for the operation using a RAM policy overview or a bucket policy.
|
API |
Action |
Description |
|
QueryVectors |
|
Queries vector data. |
Method definition
query_vectors(request: QueryVectorsRequest, **kwargs) → QueryVectorsResult
Request parameters
|
Parameter |
Type |
Description |
|
request |
QueryVectorsRequest |
Sets the request parameters, including the query vector, filter condition, and the number of results to return. For more information, see QueryVectorsRequest. |
Return values
|
Type |
Description |
|
QueryVectorsResult |
The return value, which contains a list of returned vectors. For more information, see QueryVectorsResult. |
For the complete definition of the method, see query_vectors.
Sample code
import argparse
import alibabacloud_oss_v2 as oss
import alibabacloud_oss_v2.vectors as oss_vectors
parser = argparse.ArgumentParser(description="vector query vectors sample")
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
parser.add_argument('--index_name', help='The name of the vector index.', required=True)
parser.add_argument('--account_id', help='The account id.', required=True)
def main():
args = parser.parse_args()
# Loading credentials values from the environment variables
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
# Using the SDK's default configuration
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
cfg.region = args.region
cfg.account_id = args.account_id
cfg.use_internal_endpoint = True # To access the service over the public network, set this to False or remove this line.
if args.endpoint is not None:
cfg.endpoint = args.endpoint
vector_client = oss_vectors.Client(cfg)
query_filter = {
"$and": [{
"type": {
"$nin": ["comedy", "documentary"]
}
}]
}
query_vector = {"float32": [0.1] * 128}
result = vector_client.query_vectors(oss_vectors.models.QueryVectorsRequest(
bucket=args.bucket,
index_name=args.index_name,
filter=query_filter,
query_vector=query_vector,
return_distance=True,
return_metadata=True,
top_k=10
))
print(f'status code: {result.status_code},'
f' request id: {result.request_id},'
)
if result.vectors:
for vector in result.vectors:
print(f'vector: {vector}')
if __name__ == "__main__":
main()
Reference
For the complete sample code for querying vectors, see query_vectors.py.