Code examples

Updated at:
Copy as MD

Java and Python code examples for the retrieval-augmented generation (RAG) API operations of AnalyticDB for PostgreSQL. The examples walk through the full integration flow: configure the SDK client, initialize the vector database, create a namespace and collection, then upload and query data.

Prerequisites

Before you begin, ensure that you have:

Step 1: Configure the SDK client

Install the SDK

Get the latest SDK from the Maven or pip repository. For all download links, see SDK Reference.

Java — add these dependencies to your pom.xml:

<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>gpdb20160503</artifactId>
    <version>3.12.0</version>
</dependency>

<!--  The dependency version must be this version or later. -->
<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>tea-openapi</artifactId>
    <version>0.3.1</version>
</dependency>
<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>tea</artifactId>
    <version>1.2.8</version>
</dependency>
<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>openapiutil</artifactId>
    <version>0.2.1</version>
</dependency>
<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>credentials-java</artifactId>
    <version>0.3.0</version>
</dependency>
<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>tea-util</artifactId>
    <version>0.2.21</version>
</dependency>

Python — add these packages to your requirements.txt:

alibabacloud_gpdb20160503==4.14.0
alibabacloud_tea_openapi==0.4.1

Initialize the client

All examples below use a shared getClient() / get_client() function. Credentials are read from environment variables — never hardcode them in source files.

Java

import com.aliyun.gpdb20160503.Client;
import com.aliyun.teaopenapi.models.Config;

public static Client getClient() throws Exception {
    Config config = new Config();
    config.setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"));        // Set ALIBABA_CLOUD_ACCESS_KEY_ID in your environment.
    config.setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")); // Set ALIBABA_CLOUD_ACCESS_KEY_SECRET in your environment.
    config.setRegionId("cn-beijing");        // The region where your instance resides.
    config.setEndpoint("gpdb.****uncs.com"); // Required for VPC access. For internet access, omit this parameter. See https://api.aliyun.com/product/gpdb for endpoint details.
    config.setMaxIdleConns(200);             // Set based on your client's maximum concurrent connections.
    return new Client(config);
}

Python

import os
from alibabacloud_gpdb20160503.client import Client
from alibabacloud_tea_openapi import models as open_api_models

def get_client():
    config = open_api_models.Config(
        access_key_id=os.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"),        # Set ALIBABA_CLOUD_ACCESS_KEY_ID in your environment.
        access_key_secret=os.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"), # Set ALIBABA_CLOUD_ACCESS_KEY_SECRET in your environment.
        region_id="cn-beijing",        # The region where your instance resides.
        endpoint="gpdb.****uncs.com",  # Required for VPC access. For internet access, omit this parameter. See https://api.aliyun.com/product/gpdb for endpoint details.
        max_idle_conns=200,            # Set based on your client's maximum concurrent connections.
    )
    return Client(config)

Configure timeouts

The default SDK timeout is 10 seconds. Some operations — such as UpsertChunks — support up to 60 seconds. Set the connection and read timeouts separately.

Java

config.setConnectTimeout(3000);  // Connection timeout: 3 s.
config.setReadTimeout(60000);    // Read timeout: 60 s.

Python

config.connect_timeout = 3000  # Connection timeout: 3 s.
config.read_timeout = 60000    # Read timeout: 60 s.

Configure retries

Retries are configured per API call using the ...WithOptions variant of each method.

Java

import com.aliyun.gpdb20160503.models.*;
import com.aliyun.teautil.models.RuntimeOptions;

RuntimeOptions runtime = new RuntimeOptions();
runtime.setMaxAttempts(3);  // Retry up to 3 times.
QueryCollectionDataResponse response = client.queryCollectionDataWithOptions(request, runtime);

Python

from alibabacloud_tea_util import models as util_models

runtime = util_models.RuntimeOptions(
    max_attempts=5,
)
response = client.query_collection_data_with_options(request, runtime)

Step 2: Initialize the vector database

Run this once per instance before creating any namespaces or collections.

Java

import com.aliyun.gpdb20160503.models.*;
import com.aliyun.gpdb20160503.Client;
import com.google.gson.Gson;

public static void init() throws Exception {
    String region = "cn-beijing";                  // The region where the instance resides.
    String instanceId = "gp-2zemvvolfw0d9****";    // The instance ID.
    String managerAccount = "testacc****";         // The initial account of the instance. Create it on the Account Management page in the console.
    String managerAccountPassword = "mypassword";  // The password for the account.

    InitVectorDatabaseRequest request = new InitVectorDatabaseRequest();
    request.setRegionId(region);
    request.setDBInstanceId(instanceId);
    request.setManagerAccount(managerAccount);
    request.setManagerAccountPassword(managerAccountPassword);
    Client client = getClient();
    InitVectorDatabaseResponse response = client.initVectorDatabase(request);
    System.out.println(response.getStatusCode());
    System.out.println(new Gson().toJson(response.getBody()));
}

Python

from alibabacloud_gpdb20160503.client import Client
from alibabacloud_gpdb20160503 import models as gpdb_20160503_models

def init():
    region = "cn-beijing"                  # The region where the instance resides.
    instance_id = "gp-2zemvvolfw0d9****"   # The instance ID.
    manager_account = "testacc****"        # The initial account of the instance. Create it on the Account Management page in the console.
    manager_account_password = "mypassword" # The password for the account.

    request = gpdb_20160503_models.InitVectorDatabaseRequest(
        region_id=region,
        dbinstance_id=instance_id,
        manager_account=manager_account,
        manager_account_password=manager_account_password,
    )
    response = get_client().init_vector_database(request)
    print(f"response code: {response.status_code}, body:{response.body}")

Step 3: Create a namespace

A namespace groups collections and is protected by its own password.

Java

import com.aliyun.gpdb20160503.models.*;
import com.aliyun.gpdb20160503.Client;
import com.google.gson.Gson;

public static void createNamespace() throws Exception{
    String region = "cn-beijing";                  // The region where the instance resides.
    String instanceId = "gp-2zemvvolfw0d9****";    // The instance ID.
    String managerAccount = "testacc****";         // The initial account of the instance.
    String managerAccountPassword = "mypassword";  // The password for the account.

    String namespace = "test_ns";              // The namespace name. Use only letters, digits, and underscores (_).
    String namespacePassword = "test_ns_pass"; // The password for the namespace.

    CreateNamespaceRequest request = new CreateNamespaceRequest();
    request.setRegionId(region);
    request.setDBInstanceId(instanceId);
    request.setManagerAccount(managerAccount);
    request.setManagerAccountPassword(managerAccountPassword);
    request.setNamespace(namespace);
    request.setNamespacePassword(namespacePassword);
    Client client = getClient();
    CreateNamespaceResponse response = client.createNamespace(request);
    System.out.println(response.getStatusCode());
    System.out.println(new Gson().toJson(response.getBody()));
}

Python

from alibabacloud_gpdb20160503.client import Client
from alibabacloud_gpdb20160503 import models as gpdb_20160503_models


def create_namespace():
    region = "cn-beijing"                  # The region where the instance resides.
    instance_id = "gp-2zemvvolfw0d9****"   # The instance ID.
    manager_account = "testacc****"        # The initial account of the instance.
    manager_account_password = "mypassword" # The password for the account.

    namespace = "test_ns"               # The namespace name. Use only letters, digits, and underscores (_).
    namespace_password = "test_ns_pass" # The password for the namespace.

    request = gpdb_20160503_models.CreateNamespaceRequest(
        region_id=region,
        dbinstance_id=instance_id,
        manager_account=manager_account,
        manager_account_password=manager_account_password,
        namespace=namespace,
        namespace_password=namespace_password,
    )
    response = get_client().create_namespace(request)
    print(f"response code: {response.status_code}, body:{response.body}")

Vector operations

Use vector operations when you already have embeddings and want to store and query them directly.

Create a collection

Set the vector dimension, similarity metric, metadata schema, and full-text search fields when creating a collection.

Java

import com.aliyun.gpdb20160503.models.*;
import com.aliyun.gpdb20160503.Client;
import com.google.gson.Gson;

import java.util.HashMap;
import java.util.Map;

public static void createCollection() throws Exception {
    String region = "cn-beijing";                  // The region where the instance resides.
    String instanceId = "gp-2zemvvolfw0d9****";    // The instance ID.
    String managerAccount = "testacc****";         // The initial account of the instance.
    String managerAccountPassword = "mypassword";  // The password for the account.
    String namespace = "test_ns";                  // The namespace created in the previous step.

    String collection = "test_collection"; // The collection name. Use only letters, digits, and underscores (_).
    // Metadata schema: key = column name, value = AnalyticDB for PostgreSQL field type.
    Map<String, String> metadata = new HashMap<>();
    metadata.put("doc_name", "text");
    metadata.put("title", "text");
    metadata.put("content", "text");
    metadata.put("page", "int");
    metadata.put("tags", "text[]");
    String fullTextRetrievalFields = "title,content"; // Comma-separated metadata fields to enable for full-text search.
    Long dimension = 768L;      // Vector dimension — must match your embedding model's output.
    String metrics = "cosine";  // Similarity algorithm for the vector index.

    CreateCollectionRequest request = new CreateCollectionRequest();
    request.setRegionId(region);
    request.setDBInstanceId(instanceId);
    request.setManagerAccount(managerAccount);
    request.setManagerAccountPassword(managerAccountPassword);
    request.setNamespace(namespace);
    request.setCollection(collection);
    request.setMetadata(new Gson().toJson(metadata));
    request.setFullTextRetrievalFields(fullTextRetrievalFields);
    request.setDimension(dimension);
    request.setMetrics(metrics);
    Client client = getClient();
    CreateCollectionResponse response = client.createCollection(request);
    System.out.println(response.getStatusCode());
    System.out.println(new Gson().toJson(response.getBody()));
}

Python

import json

from alibabacloud_gpdb20160503.client import Client
from alibabacloud_gpdb20160503 import models as gpdb_20160503_models

def create_collection():
    region = "cn-beijing"                  # The region where the instance resides.
    instance_id = "gp-2zemvvolfw0d9****"   # The instance ID.
    manager_account = "testacc****"        # The initial account of the instance.
    manager_account_password = "mypassword" # The password for the account.
    namespace = "test_ns"                  # The namespace created in the previous step.

    collection = "test_collection"  # The collection name. Use only letters, digits, and underscores (_).
    # Metadata schema: key = column name, value = AnalyticDB for PostgreSQL field type.
    metadata = {
        "doc_name": "text",
        "title": "text",
        "content": "text",
        "page": "int",
        "tags": "text[]",
    }
    full_text_retrieval_fields = "title,content"  # Comma-separated metadata fields to enable for full-text search.
    dimension = 768    # Vector dimension — must match your embedding model's output.
    metrics = "cosine" # Similarity algorithm for the vector index.

    request = gpdb_20160503_models.CreateCollectionRequest(
        region_id=region,
        dbinstance_id=instance_id,
        manager_account=manager_account,
        manager_account_password=manager_account_password,
        namespace=namespace,
        collection=collection,
        metadata=json.dumps(metadata),
        full_text_retrieval_fields=full_text_retrieval_fields,
        dimension=dimension,
        metrics=metrics,
    )
    response = get_client().create_collection(request)
    print(f"response code: {response.status_code}, body:{response.body}")

Upload vector data

Prepare your embedding vectors and metadata, then call UpsertCollectionData.

Java

import com.aliyun.gpdb20160503.models.*;
import com.aliyun.gpdb20160503.Client;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public static void upsertCollectionData() throws Exception {
    String region = "cn-beijing";                  // The region where the instance resides.
    String instanceId = "gp-2zemvvolfw0d9****";    // The instance ID.
    String namespace = "test_ns";                  // The created namespace.
    String namespacePassword = "test_ns_pass";     // The password for the namespace.
    String collection = "test_collection";         // The created collection.

    UpsertCollectionDataRequest request = new UpsertCollectionDataRequest();
    request.setRegionId(region);
    request.setDBInstanceId(instanceId);
    request.setNamespace(namespace);
    request.setNamespacePassword(namespacePassword);
    request.setCollection(collection);
    request.setRows(getRows());
    Client client = getClient();
    UpsertCollectionDataResponse response = client.upsertCollectionData(request);
    System.out.println(response.getStatusCode());
    System.out.println(new Gson().toJson(response.getBody()));
}

public static List<UpsertCollectionDataRequest.UpsertCollectionDataRequestRows> getRows() throws Exception {
    List<UpsertCollectionDataRequest.UpsertCollectionDataRequestRows> rows = new ArrayList<>();
    rows.add(getRow());
    return rows;
}

public static UpsertCollectionDataRequest.UpsertCollectionDataRequestRows getRow() throws Exception {
    UpsertCollectionDataRequest.UpsertCollectionDataRequestRows row = new UpsertCollectionDataRequest.UpsertCollectionDataRequestRows();
    Map<String, String> metadata = new HashMap<>();
    metadata.put("doc_name", "test.doc");
    metadata.put("title", "product");
    metadata.put("content", "product details");
    metadata.put("page", "1");
    metadata.put("tags", "{\"v1\", \"v2\"}");
    row.setMetadata(metadata);
    List<Double> vectors = new ArrayList<>();  // Replace with your own vector data.
    for (int i = 0; i < 768; i++) {
        vectors.add(Math.random());
    }
    row.setVector(vectors);
    return row;
}

Python

import json

from alibabacloud_gpdb20160503.client import Client
from alibabacloud_gpdb20160503 import models as gpdb_20160503_models
from typing import List


def upsert_collection_data():
    region = "cn-beijing"                  # The region where the instance resides.
    instance_id = "gp-2zemvvolfw0d9****"   # The instance ID.
    namespace = "test_ns"                  # The created namespace.
    namespace_password = "test_ns_pass"    # The password for the namespace.
    collection = "test_collection"         # The created collection.

    request = gpdb_20160503_models.UpsertCollectionDataRequest(
        region_id=region,
        dbinstance_id=instance_id,
        namespace=namespace,
        namespace_password=namespace_password,
        collection=collection,
        rows=get_rows(),
    )
    response = get_client().upsert_collection_data(request)
    print(f"response code: {response.status_code}, body:{response.body}")


def get_rows() -> List[gpdb_20160503_models.UpsertCollectionDataRequestRows]:
    rows = [get_row()]
    return rows


def get_row() -> gpdb_20160503_models.UpsertCollectionDataRequestRows:
    metadata = {
        "doc_name": "test.doc",
        "title": "product",
        "content": "product details",
        "page": "1",
        "tags": '["tag1", "tag2"]',
    }
    vector = []  # Replace with your own vector data.
    for i in range(768):
        vector.append(float(i))
    row = gpdb_20160503_models.UpsertCollectionDataRequestRows(
        metadata=metadata,
        vector=vector,
    )
    return row

Query vector data

Vectorize your query text first, then pass the resulting vector to QueryCollectionData.

Java

import com.aliyun.gpdb20160503.models.*;
import com.aliyun.gpdb20160503.Client;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;

public static void queryCollectionData() throws Exception {
    String region = "cn-beijing";                  // The region where the instance resides.
    String instanceId = "gp-2zemvvolfw0d9****";    // The instance ID.
    String namespace = "test_ns";                  // The created namespace.
    String namespacePassword = "test_ns_pass";     // The password for the namespace.
    String collection = "test_collection";         // The created collection.

    Long topK = 3L;  // Number of results to return.
    List<Double> vector = new ArrayList<>();  // Replace with your own vector data.
    for (int i=0;i<768;i++) {
        vector.add(Math.random());
    }

    QueryCollectionDataRequest request = new QueryCollectionDataRequest();
    request.setRegionId(region);
    request.setDBInstanceId(instanceId);
    request.setNamespace(namespace);
    request.setNamespacePassword(namespacePassword);
    request.setCollection(collection);
    request.setTopK(topK);
    request.setIncludeValues(false);
    request.setIncludeMetadataFields("title,content");
    request.setMetrics("cosine");
    request.setVector(vector);
    Client client = getClient();
    QueryCollectionDataResponse response = client.queryCollectionData(request);
    System.out.println(response.getStatusCode());
    System.out.println(new Gson().toJson(response.getBody()));
}

Python

from alibabacloud_gpdb20160503.client import Client
from alibabacloud_gpdb20160503 import models as gpdb_20160503_models


def query_collection_data():
    region = "cn-beijing"                  # The region where the instance resides.
    instance_id = "gp-2zemvvolfw0d9****"   # The instance ID.
    namespace = "test_ns"                  # The created namespace.
    namespace_password = "test_ns_pass"    # The password for the namespace.
    collection = "test_collection"         # The created collection.

    top_k = 3  # Number of results to return.
    vector = [] # Replace with your own vector data.
    for i in range(768):
        vector.append(float(i))

    request = gpdb_20160503_models.QueryCollectionDataRequest(
        region_id=region,
        dbinstance_id=instance_id,
        namespace=namespace,
        namespace_password=namespace_password,
        collection=collection,
        top_k=top_k,
        vector=vector,
        include_values=False,
        include_metadata_fields="title,content",
        metrics="cosine",
    )
    response = get_client().query_collection_data(request)
    print(f"response code: {response.status_code}, body:{response.body}")

Document operations

Use document operations when you want the service to handle embedding automatically. Instead of supplying raw vectors, you provide text and configure an embedding model on the collection.

Create a document collection

A document collection differs from a vector collection in that it takes an embeddingModel parameter. The service generates embeddings from your text automatically.

Java

import com.aliyun.gpdb20160503.models.*;
import com.aliyun.gpdb20160503.Client;
import com.google.gson.Gson;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public static void createDocumentCollection() throws Exception {
    String region = "cn-beijing";                      // The region where the instance resides.
    String instanceId = "gp-2zemvvolfw0d9****";        // The instance ID.
    String managerAccount = "testacc";                 // The initial account of the instance.
    String managerAccountPassword = "testpass";        // The password for the account.
    String namespace = "test_ns";                      // The created namespace.

    String collection = "test_doc_collection"; // The collection name. Use only letters, digits, and underscores (_).
    // Metadata schema: key = column name, value = AnalyticDB for PostgreSQL field type.
    Map<String, String> metadata = new HashMap<>();
    metadata.put("title", "text");
    metadata.put("page", "int");
    metadata.put("tags", "text[]");
    String fullTextRetrievalFields = "title";  // Comma-separated metadata fields to enable for full-text search.
    String embeddingModel = "m3e-base";        // The embedding model for automatic vectorization.
    String metrics = "cosine";                 // Similarity algorithm for the vector index.

    CreateDocumentCollectionRequest request = new CreateDocumentCollectionRequest();
    request.setRegionId(region);
    request.setDBInstanceId(instanceId);
    request.setManagerAccount(managerAccount);
    request.setManagerAccountPassword(managerAccountPassword);
    request.setNamespace(namespace);
    request.setCollection(collection);
    request.setMetadata(new Gson().toJson(metadata));
    request.setFullTextRetrievalFields(fullTextRetrievalFields);
    request.setMetrics(metrics);
    request.setEmbeddingModel(embeddingModel);
    Client client = getClient();
    CreateDocumentCollectionResponse response = client.createDocumentCollection(request);
    System.out.println(response.getStatusCode());
    System.out.println(new Gson().toJson(response.getBody()));
}

Python

import json

from alibabacloud_gpdb20160503.client import Client
from alibabacloud_gpdb20160503 import models as gpdb_20160503_models


def create_document_collection():
    region = "cn-beijing"                      # The region where the instance resides.
    instance_id = "gp-2zemvvolfw0d9****"       # The instance ID.
    manager_account = "testacc"                # The initial account of the instance.
    manager_account_password = "testpass"      # The password for the account.
    namespace = "test_ns"                      # The created namespace.

    collection = "test_doc_collection"  # The collection name. Use only letters, digits, and underscores (_).
    # Metadata schema: key = column name, value = AnalyticDB for PostgreSQL field type.
    metadata = {
        "title": "text",
        "page": "int",
        "tags": "text[]",
    }
    full_text_retrieval_fields = "title"  # Comma-separated metadata fields to enable for full-text search.
    embedding_model = "m3e-base"          # The embedding model for automatic vectorization.
    metrics = "cosine"                    # Similarity algorithm for the vector index.

    request = gpdb_20160503_models.CreateDocumentCollectionRequest(
        region_id=region,
        dbinstance_id=instance_id,
        manager_account=manager_account,
        manager_account_password=manager_account_password,
        namespace=namespace,
        collection=collection,
        metadata=json.dumps(metadata),
        full_text_retrieval_fields=full_text_retrieval_fields,
        embedding_model=embedding_model,
        metrics=metrics,
    )
    response = get_client().create_document_collection(request)
    print(f"response code: {response.status_code}, body:{response.body}")

Upload text chunks

Chunk your documents into text segments and upload them with UpsertChunks. The service embeds each chunk automatically using the collection's embedding model.

Java

import com.aliyun.gpdb20160503.models.*;
import com.aliyun.gpdb20160503.Client;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public static void upsertChunks() throws Exception {
    String region = "cn-beijing";                  // The region where the instance resides.
    String instanceId = "gp-2zemvvolfw0d9****";    // The instance ID.
    String namespace = "test_ns";                  // The created namespace.
    String namespacePassword = "test_ns_pass";     // The password for the namespace.
    String collection = "test_doc_collection";     // The created document collection.

    UpsertChunksRequest request = new UpsertChunksRequest();
    request.setRegionId(region);
    request.setDBInstanceId(instanceId);
    request.setNamespace(namespace);
    request.setNamespacePassword(namespacePassword);
    request.setCollection(collection);
    request.setTextChunks(getChunks());
    Client client = getClient();
    UpsertChunksResponse response = client.upsertChunks(request);
    System.out.println(response.getStatusCode());
    System.out.println(new Gson().toJson(response.getBody()));
}

public static List<UpsertChunksRequest.UpsertChunksRequestTextChunks> getChunks() {
    List<UpsertChunksRequest.UpsertChunksRequestTextChunks> textChunks = new ArrayList<>();
    textChunks.add(getChunk());
    return textChunks;
}

public static UpsertChunksRequest.UpsertChunksRequestTextChunks getChunk() {
    UpsertChunksRequest.UpsertChunksRequestTextChunks chunk = new UpsertChunksRequest.UpsertChunksRequestTextChunks();
    chunk.setContent("Test text");  // Replace with your own text.
    Map<String, Object> metadata = new HashMap<>();
    metadata.put("title", "product");
    metadata.put("page", 1);
    metadata.put("tags", Arrays.asList("v1", "v2"));
    chunk.setMetadata(metadata);
    return chunk;
}

Python

from alibabacloud_gpdb20160503.client import Client
from alibabacloud_gpdb20160503 import models as gpdb_20160503_models
from typing import List


def upsert_chunks():
    region = "cn-beijing"                  # The region where the instance resides.
    instance_id = "gp-2zemvvolfw0d9****"   # The instance ID.
    namespace = "test_ns"                  # The created namespace.
    namespace_password = "test_ns_pass"    # The password for the namespace.
    collection = "test_doc_collection"     # The created document collection.

    request = gpdb_20160503_models.UpsertChunksRequest(
        region_id=region,
        dbinstance_id=instance_id,
        namespace=namespace,
        namespace_password=namespace_password,
        collection=collection,
        text_chunks=get_chunks(),
    )
    response = get_client().upsert_chunks(request)
    print(f"response code: {response.status_code}, body:{response.body}")


def get_chunks() -> List[gpdb_20160503_models.UpsertChunksRequestTextChunks]:
    chunks = [get_chunk()]
    return chunks


def get_chunk() -> gpdb_20160503_models.UpsertChunksRequestTextChunks:
    content = "Test text"  # Replace with your own text.
    metadata = {
        "title": "product",
        "page": 1,
        "tags": ["tag1", "tag2"],
    }
    chunk = gpdb_20160503_models.UpsertChunksRequestTextChunks(
        content=content,
        metadata=metadata,
    )
    return chunk

Upload a document asynchronously

UploadDocumentAsync uploads a local file and processes it in the background. After submitting, poll GetUploadDocumentJob every 5 seconds until job.completed is true or job.status is Failed, Cancelling, or Cancelled.

Java

import com.aliyun.gpdb20160503.Client;
import com.aliyun.gpdb20160503.models.*;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import com.google.gson.Gson;

import java.io.File;
import java.nio.file.Files;
import java.util.*;
import java.util.concurrent.*;

private static final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

public static void uploadDocument() throws Exception {
    String region = "cn-beijing";                  // The region where the instance resides.
    String instanceId = "gp-2zemvvolfw0d9****";    // The instance ID.
    String namespace = "test_ns";                  // The created namespace.
    String namespacePassword = "test_ns_pass";     // The password for the namespace.
    String collection = "test_doc_collection";     // The created document collection.

    String fileName = "test_file.txt";             // The local filename, including the extension.
    String localFilePath = "/root/test_file.txt";  // The local file path.
    Map<String, Object> metadata = new HashMap<>();
    metadata.put("title", "product");
    metadata.put("tags", Arrays.asList("v1", "v2"));

    UploadDocumentAsyncAdvanceRequest request = new UploadDocumentAsyncAdvanceRequest();
    request.setRegionId(region);
    request.setDBInstanceId(instanceId);
    request.setNamespace(namespace);
    request.setNamespacePassword(namespacePassword);
    request.setCollection(collection);
    request.setFileName(fileName);
    request.setMetadata(metadata);
    request.setFileUrlObject(Files.newInputStream(new File(localFilePath).toPath()));

    Client client = getClient();
    RuntimeOptions runtime = new RuntimeOptions();
    UploadDocumentAsyncResponse response = client.uploadDocumentAsyncAdvance(request, runtime);
    System.out.println(response.getStatusCode());
    System.out.println(new Gson().toJson(response.getBody()));

    Callable<String> waitUploadDocumentJobDone = () -> getUploadDocumentJobStatus(client, response.getBody().getJobId());
    try {
        String result = executeWithTimeout(waitUploadDocumentJobDone, 1, TimeUnit.HOURS);
        System.out.println("Task result: " + result);
    } catch (InterruptedException | ExecutionException | TimeoutException e) {
        e.printStackTrace();
    }
}

public static String getUploadDocumentJobStatus(Client client, String jobId) {
    String region = "cn-beijing";                  // The region where the instance resides.
    String instanceId = "gp-2zemvvolfw0d9****";    // The instance ID.
    String namespace = "test_ns";                  // The created namespace.
    String namespacePassword = "test_ns_pass";     // The password for the namespace.
    String collection = "test_doc_collection";     // The created document collection.

    GetUploadDocumentJobRequest request = new GetUploadDocumentJobRequest();
    request.setRegionId(region);
    request.setDBInstanceId(instanceId);
    request.setNamespace(namespace);
    request.setNamespacePassword(namespacePassword);
    request.setCollection(collection);
    request.setJobId(jobId);

    // Stop polling when job.getCompleted() is true or status is one of the terminal values below.
    List<String> nonSuccessStatuses = Arrays.asList("Failed", "Cancelling", "Cancelled");
    int i = 0;
    while (true) {
        System.out.println("Attempt " + (i + 1) + "...");
        try {
            GetUploadDocumentJobResponse response = client.getUploadDocumentJob(request);
            System.out.println(response.getStatusCode());
            System.out.println(new Gson().toJson(response.getBody()));
            if (response.getBody().getJob().getCompleted()) {
                return response.getBody().getJob().getStatus();
            } else if (nonSuccessStatuses.contains(response.getBody().getJob().getStatus())) {
                return response.getBody().getJob().getStatus();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "Failed";
        }
        try {
            Thread.sleep(5000); // Retry every 5 seconds.
        } catch (InterruptedException e) {
            return "Interrupted";
        }
        i++;
    }
}

public static <T> T executeWithTimeout(Callable<T> task, long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
    Future<T> future = null;
    try {
        future = scheduler.submit(task);
        return future.get(timeout, unit); // Wait for the task to complete or time out.
    } catch (TimeoutException e) {
        if (future != null) {
            future.cancel(true); // Cancel the task.
        }
        throw new TimeoutException("Task execution timed out");
    } finally {
        scheduler.shutdown(); // Shut down the scheduler.
    }
}

Python

import json
import io
import concurrent.futures
import time

from alibabacloud_gpdb20160503.client import Client
from alibabacloud_gpdb20160503 import models as gpdb_20160503_models
from alibabacloud_tea_util import models as util_models
from typing import List


def upload_document():
    region = "cn-beijing"                  # The region where the instance resides.
    instance_id = "gp-2zemvvolfw0d9****"   # The instance ID.
    namespace = "test_ns"                  # The created namespace.
    namespace_password = "test_ns_pass"    # The password for the namespace.
    collection = "test_doc_collection"     # The created document collection.

    metadata = {
        "title": "product",
        "tags": ["tag1", "tag2"],
    }
    file_name = "test_file.txt"            # The local filename, including the extension.
    local_file_path = "/root/test_file.txt" # The local file path.
    with open(local_file_path, 'rb') as file:
        file_content = file.read()
    request = gpdb_20160503_models.UploadDocumentAsyncAdvanceRequest(
        region_id=region,
        dbinstance_id=instance_id,
        namespace=namespace,
        namespace_password=namespace_password,
        collection=collection,
        file_name=file_name,
        metadata=metadata,
        file_url_object=io.BytesIO(file_content),
    )
    client = get_client()
    response = client.upload_document_async_advance(request, util_models.RuntimeOptions())
    print(f"response code: {response.status_code}, body:{response.body}")

    def get_upload_document_job_status_wrapper():
        return get_upload_document_job_status(client, response.body.job_id)
    try:
        result = execute_with_timeout(get_upload_document_job_status_wrapper, 3600)  # Timeout: 1 hour.
        print(f"Task result: {result}")
    except TimeoutError as e:
        print(e)


def get_upload_document_job_status(client, job_id):
    region = "cn-beijing"                  # The region where the instance resides.
    instance_id = "gp-2zemvvolfw0d9****"   # The instance ID.
    namespace = "test_ns"                  # The created namespace.
    namespace_password = "test_ns_pass"    # The password for the namespace.
    collection = "test_doc_collection"     # The created document collection.

    request = gpdb_20160503_models.GetUploadDocumentJobRequest(
        region_id=region,
        dbinstance_id=instance_id,
        namespace=namespace,
        namespace_password=namespace_password,
        collection=collection,
        job_id=job_id,
    )

    # Stop polling when job.completed is True or status is one of the terminal values below.
    non_success_statuses = ["Failed", "Cancelling", "Cancelled"]
    i = 0
    while True:
        print(f"Attempt {i + 1}...")
        response: gpdb_20160503_models.GetUploadDocumentJobResponse = client.get_upload_document_job(request)
        print(f"response code: {response.status_code}, body:{response.body}")
        if response.body.job.completed or response.body.job.status in non_success_statuses:
            return response.body.job.status
        time.sleep(5)  # Retry every 5 seconds.
        i += 1


def execute_with_timeout(task, timeout):
    with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor:
        future = executor.submit(task)
        try:
            result = future.result(timeout=timeout)
            return result
        except concurrent.futures.TimeoutError:
            future.cancel()  # Cancel the task.
            raise TimeoutError("Task execution timed out")

Query document data

Pass a text string directly to QueryContent — no pre-embedding required. The service vectorizes the query and returns the top-K matching chunks.

Java

import com.aliyun.gpdb20160503.Client;
import com.aliyun.gpdb20160503.models.*;
import com.google.gson.Gson;

import java.util.*;

public static void queryContent() throws Exception {
    String region = "cn-beijing";                  // The region where the instance resides.
    String instanceId = "gp-2zemvvolfw0d9****";    // The instance ID.
    String namespace = "test_ns";                  // The created namespace.
    String namespacePassword = "test_ns_pass";     // The password for the namespace.
    String collection = "test_doc_collection";     // The created document collection.

    String content = "Test text";                  // The query text.
    String includeMetadataFields = "title,tags";   // Metadata fields to include in the response.
    String metrics = "cosine";                     // Similarity algorithm.
    Integer topK = 10;                             // Number of results to return.

    QueryContentRequest request = new QueryContentRequest();
    request.setRegionId(region);
    request.setDBInstanceId(instanceId);
    request.setNamespace(namespace);
    request.setNamespacePassword(namespacePassword);
    request.setCollection(collection);
    request.setContent(content);
    request.setIncludeMetadataFields(includeMetadataFields);
    request.setMetrics(metrics);
    request.setTopK(topK);
    Client client = getClient();
    QueryContentResponse response = client.queryContent(request);
    System.out.println(response.getStatusCode());
    System.out.println(new Gson().toJson(response.getBody()));
}

Python

from alibabacloud_gpdb20160503.client import Client
from alibabacloud_gpdb20160503 import models as gpdb_20160503_models


def query_content():
    region = "cn-beijing"                  # The region where the instance resides.
    instance_id = "gp-2zemvvolfw0d9****"   # The instance ID.
    namespace = "test_ns"                  # The created namespace.
    namespace_password = "test_ns_pass"    # The password for the namespace.
    collection = "test_doc_collection"     # The created document collection.

    content = "Test text"                  # The query text.
    include_metadata_fields = "title,tags" # Metadata fields to include in the response.
    metrics = "cosine"                     # Similarity algorithm.
    top_k = 10                             # Number of results to return.

    request = gpdb_20160503_models.QueryContentRequest(
        region_id=region,
        dbinstance_id=instance_id,
        namespace=namespace,
        namespace_password=namespace_password,
        collection=collection,
        content=content,
        include_metadata_fields=include_metadata_fields,
        metrics=metrics,
        top_k=top_k,
    )
    response = get_client().query_content(request)
    print(f"response code: {response.status_code}, body:{response.body}")