All Products
Search
Document Center

OpenSearch:Query data

Last Updated:Jun 17, 2024

This topic describes how to use OpenSearch Vector Search Edition SDKs for Java in asynchronous mode, Java, Python, and Go to perform vector-based queries, prediction-based queries, and queries by using filter conditions.

Dependencies

Java in asynchronous mode

<dependency>
  <groupId>com.aliyun</groupId>
  <artifactId>aliyun-sdk-ha3engine-async</artifactId>
  <version>1.0.0</version>
</dependency>

Java

<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>aliyun-sdk-ha3engine-vector</artifactId>
    <version>1.1.1</version>
</dependency>

Python

#Requires: Python >=3.6
pip install alibabacloud-ha3engine-vector

Go

go get github.com/aliyun/alibabacloud-ha3-go-sdk@v1.1.3-vector

Parameter description

You must specify the following parameters in the SDKs for Java and Python: endpoint, instance_id, access_user_name, and access_pass_word.

  • endpoint: the internal or public endpoint.

You can view the endpoints in the Network Information and API Endpoint sections of the Instance Details page.

image.png

After you turn on Public Access, you can access the OpenSearch Vector Search Edition instance by using a public endpoint on your on-premises machine. A public endpoint contains the word "public". For more information about how to configure a whitelist of IP addresses, see the Network Information section of the "Instance details" topic.

If you use an Elastic Compute Service (ECS) instance to access the OpenSearch Vector Search Edition instance, you can specify the same vSwitch as that of the ECS instance to access the OpenSearch Vector Search Edition instance by using the API endpoint.

  • instance_id: the ID of the OpenSearch Vector Search Edition instance.

image.png

  • access_user_name: the username.

  • access_pass_word: the password.

You can view the username and password in the API Endpoint section of the Instance Details page. The password is specified when you purchase the instance and can be modified.

image.png

Vector-based query

Simple query

Java in asynchronous mode

package com.aliyun.ha3engine;

import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

import com.aliyun.ha3engine.async.AsyncClient;
import com.aliyun.ha3engine.async.models.QueryRequest;
import com.aliyun.ha3engine.async.models.SearchResponse;
import com.aliyun.sdk.ha3engine.async.core.AsyncConfigInfoProvider;
import com.aliyun.tea.TeaException;

import darabonba.core.client.ClientOverrideConfiguration;

/**
 * @author alibaba
 */
public class SearchDoc {

    public static void main(String[] args) throws Exception {
        try {
            // The username and password that are used to access the instance. You can view the username and password in the API Endpoint section of the Instance Details page.
            AsyncConfigInfoProvider provider = AsyncConfigInfoProvider.create("username", "password");

            // Initialize the asynchronous client.
            AsyncClient client = AsyncClient.builder()
                    .credentialsProvider(provider)
                    .overrideConfiguration(
                            ClientOverrideConfiguration.create()
                                    // The public endpoint of the instance. You can view the public endpoint in the Network Information section of the Instance Details page.
                                    .setEndpointOverride("ha-cn-***********.public.ha.aliyuncs.com")
                            .setProtocol("http")
                    ).build();
            QueryRequest queryRequest = QueryRequest.builder()
                    .tableName("table_name") // The name of the table to be queried.
                    .indexName("index_name") // The name of the index to be queried.
                    .vector(Arrays.asList(0.0001575F, 0.00682848F)) // The vector data to be queried.
                    .topK(10) // The number of results to be returned.
                    .includeVector(true) // Specifies whether to return the vector information in documents.
                    .build();
            CompletableFuture<SearchResponse> responseCompletableFuture = client.query(queryRequest);
            String responseBody = responseCompletableFuture.get().getBody();

            System.out.println("result: " + responseBody);

        } catch (ExecutionException | InterruptedException e) {
            System.out.println(e.getMessage());
        } catch (TeaException e) {
            System.out.println(e.getMessage());
            Map<String, Object> abc = e.getData();
            System.out.println(com.aliyun.teautil.Common.toJSONString(abc));
        }
    }
}

Java

package com.aliyun.ha3engine.demo;

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

import com.aliyun.ha3engine.vector.Client;
import com.aliyun.ha3engine.vector.models.Config;
import com.aliyun.ha3engine.vector.models.QueryRequest;
import com.aliyun.ha3engine.vector.models.SearchResponse;
import com.aliyun.tea.TeaException;

import org.junit.Before;
import org.junit.Test;

public class Demo {

    /**
     * The engine client of the OpenSearch Vector Search Edition instance. The client supports query operations.
     */
    private Client client;

    @Before
    public void clientInit() throws Exception {

        /*
          Initialize the engine client.
         */
        Config config = new Config();

        // The name of the OpenSearch Vector Search Edition instance. You can view the instance name in the upper-left corner of the Instance Details page. Example: ha-cn-i7*****605.
        config.setInstanceId("ha-cn-i7*****605");

        // The username. You can view the username in the API Endpoint section of the Instance Details page.
        config.setAccessUserName("username");

        // The password. You can modify the password in the API Endpoint section of the Instance Details page.
        config.setAccessPassWord("password");

        // To access the instance by using an internal endpoint, specify the endpoint. To access the instance by using a public endpoint, uncomment the following line:
        config.setEndpoint("ha-cn-i7*****605.public.ha.aliyuncs.com");
        // To access the instance over the Internet, uncomment the following line and specify the HTTP proxy.
        //        config.setHttpProxy("http://116.62.XXX.XXX:80");

        client = new Client(config);

    }

    @Test
    public void query() throws Exception {
        try {
            QueryRequest request = new QueryRequest();
            request.setTableName("gist"); // Required. The name of the table to be queried.
            request.setVector(Arrays.asList(0.183762561f, 0.738372617f)); // Required. The vector data to be queried.
            request.setTopK(100); // Optional. The number of results to be returned.
            request.setIncludeVector(true); // Optional. Specifies whether to return the vector information in documents.
            request.setSearchParams("{\\\"qc.searcher.scan_ratio\\\":0.01}");
            SearchResponse searchResponse = client.query(request);
            System.out.println("Result:\n" + searchResponse.getBody());
        } catch (TeaException e) {
            System.out.println(e.getCode());
            System.out.println(e.getMessage());
            Map<String, Object> abc = e.getData();
            System.out.println(com.aliyun.teautil.Common.toJSONString(abc));
        }
    }

}

Python

from alibabacloud_ha3engine_vector.client import Client
from alibabacloud_ha3engine_vector.models import Config
from alibabacloud_ha3engine_vector.models import QueryRequest

config = Config(
        # To access the instance by using an internal endpoint, specify the endpoint.
        endpoint="ha-cn-7mz2ougaw02.ha.aliyuncs.com",
        # The name of the OpenSearch Vector Search Edition instance. You can view the instance name in the upper-left corner of the Instance Details page. Example: ha-cn-i7*****605.
        instance_id="ha-cn-7mz2ougaw02",
        # The username. You can view the username in the API Endpoint section of the Instance Details page.
        access_user_name="user",
        # The password. You can modify the password in the API Endpoint section of the Instance Details page.
        access_pass_word="111111")
client = Client(config)

request = QueryRequest(table_name="gist",
                        vector=[0.1, 0.2, 0.3],
                      include_vector=True,
                      search_params="{\\\"qc.searcher.scan_ratio\\\":0.01}",
                      top_k=10)
result = client.query(request)

Go

package main

import (
	"fmt"
	"github.com/alibabacloud-go/tea/tea"
	ha3engine "github.com/aliyun/alibabacloud-ha3-go-sdk/client"
)

func main() {

	// Create a Config instance.
	config := &ha3engine.Config{
		// The internal or public endpoint.
		Endpoint: tea.String("<Endpoint>"),
		// The name of the OpenSearch Vector Search Edition instance. You can view the instance name in the upper-left corner of the Instance Details page. Example: ha-cn-i7*****605.
		InstanceId: tea.String("<InstanceId>"),
		// The username. You can view the username in the API Endpoint section of the Instance Details page.
		AccessUserName: tea.String("<AccessUserName>"),
		// The password. You can modify the password in the API Endpoint section of the Instance Details page.
		AccessPassWord: tea.String("<AccessPassWord>"),
	}

	// Initialize a client for sending requests.
	client, _clientErr := ha3engine.NewClient(config)

	// If an error occurs when the system creates the client, _clientErr and an error message are returned.
	if _clientErr != nil {
		fmt.Println(_clientErr)
		return
	}

	query(client)
}

/**
 * Simple query
 */
func query(client *ha3engine.Client) {

	searchRequestModel := &ha3engine.QueryRequest{}
	searchRequestModel.SetTableName("api")

	// Create an array of 32-bit floating-point numbers.
	array := make([]*float32, 3)

	// Allocate a memory address to each value of the array and initialize the values.
	value1 := float32(1.23)
	value2 := float32(4.56)
	value3 := float32(7.89)

	// Assign values to the elements of the array.
	array[0] = &value1
	array[1] = &value2
	array[2] = &value3

	searchRequestModel.SetVector(array)

	response, _requestErr := client.Query(searchRequestModel)

	// If an error occurs when the system sends the request, _requestErr and an error message are returned.
	if _requestErr != nil {
		fmt.Println(_requestErr)
		return
	}

	// Display the response if no error occurs.
	fmt.Println(response)

}

Query based on multiple vectors

You can specify multiple vectors to perform a vector-based query. The system merges and sorts the retrieved results, and returns the top K results.

Java

package com.aliyun.ha3engine.demo;

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

import com.aliyun.ha3engine.vector.Client;
import com.aliyun.ha3engine.vector.models.Config;
import com.aliyun.ha3engine.vector.models.QueryRequest;
import com.aliyun.ha3engine.vector.models.SearchResponse;
import com.aliyun.tea.TeaException;

import org.junit.Before;
import org.junit.Test;

public class Demo {

    /**
     * The engine client of the OpenSearch Vector Search Edition instance. The client supports query operations.
     */
    private Client client;

    @Before
    public void clientInit() throws Exception {

        /*
          Initialize the engine client.
         */
        Config config = new Config();

        // The name of the OpenSearch Vector Search Edition instance. You can view the instance name in the upper-left corner of the Instance Details page. Example: ha-cn-i7*****605.
        config.setInstanceId("ha-cn-i7*****605");

        // The username. You can view the username in the API Endpoint section of the Instance Details page.
        config.setAccessUserName("username");

        // The password. You can modify the password in the API Endpoint section of the Instance Details page.
        config.setAccessPassWord("password");

        // To access the instance by using an internal endpoint, specify the endpoint. To access the instance by using a public endpoint, uncomment the following line:
        config.setEndpoint("ha-cn-i7*****605.public.ha.aliyuncs.com");
        // To access the instance over the Internet, uncomment the following line and specify the HTTP proxy.
//        config.setHttpProxy("http://116.62.XXX.XXX:80");

        client = new Client(config);

    }

    @Test
    public void query() throws Exception {
        try {
            QueryRequest request = new QueryRequest();
            request.setTableName("gist"); // Required. The name of the table to be queried.
            request.setVector(Arrays.asList(0.1f, 0.2f, 0.3f, 0.4f)); // Required. The vector data to be queried.
            request.setVectorCount(2); // Optional. The number of vectors contained in the vector field.
            request.setTopK(100); // Optional. The number of results to be returned.
            request.setIncludeVector(true); // Optional. Specifies whether to return the vector information in documents.
            request.setOutputFields(new ArrayList<String>()); // Optional. The fields to be returned.
            request.setFilter("a>10"); // Optional. The filter expression.
            request.setSearchParams("{\\\"qc.searcher.scan_ratio\\\":0.01}");
            SearchResponse searchResponse = client.query(request);
            System.out.println("Result:\n" + searchResponse.getBody());
        } catch (TeaException e) {
            System.out.println(e.getCode());
            System.out.println(e.getMessage());
            Map<String, Object> abc = e.getData();
            System.out.println(com.aliyun.teautil.Common.toJSONString(abc));
        }
    }

}

Python

from alibabacloud_ha3engine_vector.client import Client
from alibabacloud_ha3engine_vector.models import Config
from alibabacloud_ha3engine_vector.models import QueryRequest

config = Config(
        # To access the instance by using an internal endpoint, specify the endpoint.
        endpoint="ha-cn-7mz2ougaw02.ha.aliyuncs.com",
        # The name of the OpenSearch Vector Search Edition instance. You can view the instance name in the upper-left corner of the Instance Details page. Example: ha-cn-i7*****605.
        instance_id="ha-cn-7mz2ougaw02",
        # The username. You can view the username in the API Endpoint section of the Instance Details page.
        access_user_name="user",
        # The password. You can modify the password in the API Endpoint section of the Instance Details page.
        access_pass_word="111111")
client = Client(config)

request = QueryRequest(table_name="t1",
                        vector=[0.1, 0.2, 0.3, 0.4],
                        vector_count=2,
                        include_vector=True,
                        filter="a > 10",
                        search_params="{\\\"qc.searcher.scan_ratio\\\":0.01}",
                        output_fields=["a", "b"],
                        top_k=10)
result = client.query(request)

Namespace-based query

OpenSearch Vector Search Edition allows you to partition indexes by using namespaces. After you configure namespaces for vector indexes, you can specify a namespace to query data. This way, you can query different subsets of indexes by sending different query requests.

Note: If you configure a namespace for a vector index, you must specify the namespace when you query data.

package com.aliyun.ha3engine.demo;

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

import com.aliyun.ha3engine.vector.Client;
import com.aliyun.ha3engine.vector.models.Config;
import com.aliyun.ha3engine.vector.models.QueryRequest;
import com.aliyun.ha3engine.vector.models.SearchResponse;
import com.aliyun.tea.TeaException;

import org.junit.Before;
import org.junit.Test;

public class Demo {

    /**
     * The engine client of the OpenSearch Vector Search Edition instance. The client supports query operations.
     */
    private Client client;

    @Before
    public void clientInit() throws Exception {

        /*
          Initialize the engine client.
         */
        Config config = new Config();

        // The name of the OpenSearch Vector Search Edition instance. You can view the instance name in the upper-left corner of the Instance Details page. Example: ha-cn-i7*****605.
        config.setInstanceId("ha-cn-i7*****605");

        // The username. You can view the username in the API Endpoint section of the Instance Details page.
        config.setAccessUserName("username");

        // The password. You can modify the password in the API Endpoint section of the Instance Details page.
        config.setAccessPassWord("password");

        // To access the instance by using an internal endpoint, specify the endpoint. To access the instance by using a public endpoint, uncomment the following line:
        config.setEndpoint("ha-cn-i7*****605.public.ha.aliyuncs.com");
        // To access the instance over the Internet, uncomment the following line and specify the HTTP proxy.
//        config.setHttpProxy("http://116.62.XXX.XXX:80");

        client = new Client(config);

    }

    @Test
    public void query() throws Exception {
        try {
            QueryRequest request = new QueryRequest();
            request.setTableName("gist"); // Required. The name of the table to be queried.
            request.setVector(Arrays.asList(0.183762561f, 0.738372617f)); // Required. The vector data to be queried.
            request.setNamespace("namespace"); // Optional. The namespace of the vector to be queried.
            request.setTopK(100); // Optional. The number of results to be returned.
            request.setIncludeVector(true); // Optional. Specifies whether to return the vector information in documents.
            request.setSearchParams("{\\\"qc.searcher.scan_ratio\\\":0.01}");
            SearchResponse searchResponse = client.query(request);
            System.out.println("Result:\n" + searchResponse.getBody());
        } catch (TeaException e) {
            System.out.println(e.getCode());
            System.out.println(e.getMessage());
            Map<String, Object> abc = e.getData();
            System.out.println(com.aliyun.teautil.Common.toJSONString(abc));
        }
    }

}
from alibabacloud_ha3engine_vector.client import Client
from alibabacloud_ha3engine_vector.models import Config
from alibabacloud_ha3engine_vector.models import QueryRequest

config = Config(
        # To access the instance by using an internal endpoint, specify the endpoint.
        endpoint="ha-cn-7mz2ougaw02.ha.aliyuncs.com",
        # The name of the OpenSearch Vector Search Edition instance. You can view the instance name in the upper-left corner of the Instance Details page. Example: ha-cn-i7*****605.
        instance_id="ha-cn-7mz2ougaw02",
        # The username. You can view the username in the API Endpoint section of the Instance Details page.
        access_user_name="user",
        # The password. You can modify the password in the API Endpoint section of the Instance Details page.
        access_pass_word="111111")
client = Client(config)

request = QueryRequest(table_name="t1",
                        namespace="space_b",
                        vector=[0.1, 0.2],
                        include_vector=True,
                        search_params="{\\\"qc.searcher.scan_ratio\\\":0.01}",
                        top_k=10)
result = client.query(request)

Query based on multiple namespaces

If you configure namespaces for vector indexes, you can query data in multiple namespaces.

package com.aliyun.ha3engine.demo;

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

import com.aliyun.ha3engine.vector.Client;
import com.aliyun.ha3engine.vector.models.*;
import com.aliyun.tea.TeaException;

import org.junit.Before;
import org.junit.Test;

public class Demo {

    /**
     * The engine client of the OpenSearch Vector Search Edition instance. The client supports query operations.
     */
    private Client client;

    @Before
    public void clientInit() throws Exception {

        /*
          Initialize the engine client.
         */
        Config config = new Config();

        // The name of the OpenSearch Vector Search Edition instance. You can view the instance name in the upper-left corner of the Instance Details page. Example: ha-cn-i7*****605.
        config.setInstanceId("ha-cn-i7*****605");

        // The username. You can view the username in the API Endpoint section of the Instance Details page.
        config.setAccessUserName("username");

        // The password. You can modify the password in the API Endpoint section of the Instance Details page.
        config.setAccessPassWord("password");

        // To access the instance by using an internal endpoint, specify the endpoint. To access the instance by using a public endpoint, uncomment the following line:
        config.setEndpoint("ha-cn-i7*****605.public.ha.aliyuncs.com");
        // To access the instance over the Internet, uncomment the following line and specify the HTTP proxy.
//        config.setHttpProxy("http://116.62.XXX.XXX:80");

        client = new Client(config);

    }

    @Test
    public void multiQuery() throws Exception {
        try {
            MultiQueryRequest request = new MultiQueryRequest();
            request.setTableName("gist");
            request.setTopK(3);
            request.setIncludeVector(true);

            QueryRequest query1 = new Query();
            query1.setVector(Arrays.asList(0.1f, 0.2f, 0.3f));
            query1.setNamespace("space_a");

            QueryRequest query2 = new Query();
            query2.setVector(Arrays.asList(0.1f, 0.2f, 0.3f));
            query2.setNamespace("space_b");

            request.setQueries(Arrays.asList(query1, query2));
							
            SearchResponse searchResponse = client.multiQuery(request);
            System.out.println("Result:\n" + searchResponse.getBody());
        } catch (TeaException e) {
            System.out.println(e.getCode());
            System.out.println(e.getMessage());
            Map<String, Object> abc = e.getData();
            System.out.println(com.aliyun.teautil.Common.toJSONString(abc));
        }
    }

}
from alibabacloud_ha3engine_vector.client import Client
from alibabacloud_ha3engine_vector.models import Config
from alibabacloud_ha3engine_vector.models import QueryRequest
from alibabacloud_ha3engine_vector.models import MultiQueryRequest

config = Config(
        # To access the instance by using an internal endpoint, specify the endpoint.
        endpoint="ha-cn-7mz2ougaw02.ha.aliyuncs.com",
        # The name of the OpenSearch Vector Search Edition instance. You can view the instance name in the upper-left corner of the Instance Details page. Example: ha-cn-i7*****605.
        instance_id="ha-cn-7mz2ougaw02",
        # The username. You can view the username in the API Endpoint section of the Instance Details page.
        access_user_name="user",
        # The password. You can modify the password in the API Endpoint section of the Instance Details page.
        access_pass_word="111111")
client = Client(config)

q1 = QueryRequest(vector=[0.1, 0.2, 0.3], namespace="space_a")
q2 = QueryRequest(vector=[0.4, 0.5, 0.6], namespace="space_b")
request = MultiQueryRequest(table_name = "gist", 
                                 queries=[q1, q2], 
                                 top_k=3, 
                                 include_vector=True)
result = client.multi_query(request)

Query by using filter conditions

You can use filter expressions to specify filter conditions for data queries.

package com.aliyun.ha3engine.demo;

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

import com.aliyun.ha3engine.vector.Client;
import com.aliyun.ha3engine.vector.models.Config;
import com.aliyun.ha3engine.vector.models.QueryRequest;
import com.aliyun.ha3engine.vector.models.SearchResponse;
import com.aliyun.tea.TeaException;

import org.junit.Before;
import org.junit.Test;

public class Demo {

    /**
     * The engine client of the OpenSearch Vector Search Edition instance. The client supports query operations.
     */
    private Client client;

    @Before
    public void clientInit() throws Exception {

        /*
          Initialize the engine client.
         */
        Config config = new Config();

        // The name of the OpenSearch Vector Search Edition instance. You can view the instance name in the upper-left corner of the Instance Details page. Example: ha-cn-i7*****605.
        config.setInstanceId("ha-cn-i7*****605");

        // The username. You can view the username in the API Endpoint section of the Instance Details page.
        config.setAccessUserName("username");

        // The password. You can modify the password in the API Endpoint section of the Instance Details page.
        config.setAccessPassWord("password");

        // To access the instance by using an internal endpoint, specify the endpoint. To access the instance by using a public endpoint, uncomment the following line:
        config.setEndpoint("ha-cn-i7*****605.public.ha.aliyuncs.com");
        // To access the instance over the Internet, uncomment the following line and specify the HTTP proxy.
//        config.setHttpProxy("http://116.62.XXX.XXX:80");

        client = new Client(config);

    }

    @Test
    public void query() throws Exception {
        try {
            QueryRequest request = new QueryRequest();
            request.setTableName("gist"); // Required. The name of the table to be queried.
            request.setVector(Arrays.asList(0.183762561f, 0.738372617f)); // Required. The vector data to be queried.
            request.setTopK(100); // Optional. The number of results to be returned.
            request.setIncludeVector(true); // Optional. Specifies whether to return the vector information in documents.
            request.setOutputFields(new ArrayList<String>()); // Optional. The fields to be returned.
            request.setFilter("a>10"); // Optional. The filter expression.
            request.setSearchParams("{\\\"qc.searcher.scan_ratio\\\":0.01}");
            SearchResponse searchResponse = client.query(request);
            System.out.println("Result:\n" + searchResponse.getBody());
        } catch (TeaException e) {
            System.out.println(e.getCode());
            System.out.println(e.getMessage());
            Map<String, Object> abc = e.getData();
            System.out.println(com.aliyun.teautil.Common.toJSONString(abc));
        }
    }

}
from alibabacloud_ha3engine_vector.client import Client
from alibabacloud_ha3engine_vector.models import Config
from alibabacloud_ha3engine_vector.models import QueryRequest

config = Config(
        # To access the instance by using an internal endpoint, specify the endpoint.
        endpoint="ha-cn-7mz2ougaw02.ha.aliyuncs.com",
        # The name of the OpenSearch Vector Search Edition instance. You can view the instance name in the upper-left corner of the Instance Details page. Example: ha-cn-i7*****605.
        instance_id="ha-cn-7mz2ougaw02",
        # The username. You can view the username in the API Endpoint section of the Instance Details page.
        access_user_name="user",
        # The password. You can modify the password in the API Endpoint section of the Instance Details page.
        access_pass_word="111111")
client = Client(config)

request = QueryRequest(table_name="t1",
                        vector=[0.1, 0.2],
                        include_vector=True,
                        filter="a > 10",
                        output_fields=["a", "b"],
                        search_params="{\\\"qc.searcher.scan_ratio\\\":0.01}",
                        top_k=10)
result = client.query(request)

For more information about how to use filter expressions, see Filter expression.

Primary key-based query

Java in asynchronous mode

package com.aliyun.ha3engine;

import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

import com.aliyun.ha3engine.async.AsyncClient;
import com.aliyun.ha3engine.async.models.MultiQueryRequest;
import com.aliyun.ha3engine.async.models.QueryRequest;
import com.aliyun.ha3engine.async.models.SearchResponse;
import com.aliyun.sdk.ha3engine.async.core.AsyncConfigInfoProvider;
import com.aliyun.tea.TeaException;

import darabonba.core.client.ClientOverrideConfiguration;

/**
 * @author alibaba
 */
public class SearchDoc {

    public static void main(String[] args) throws Exception {
        try {
            // The username and password that are used to access the instance. You can view the username and password in the API Endpoint section of the Instance Details page.
            AsyncConfigInfoProvider provider = AsyncConfigInfoProvider.create("username", "password");

            // Initialize the asynchronous client.
            AsyncClient client = AsyncClient.builder()
                    .credentialsProvider(provider)
                    .overrideConfiguration(
                            ClientOverrideConfiguration.create()
                                    // The public endpoint of the instance. You can view the public endpoint in the Network Information section of the Instance Details page.
                                    .setEndpointOverride("ha-cn-***********.public.ha.aliyuncs.com")
                            .setProtocol("http")
                    ).build();
            FetchRequest fetchRequest = FetchRequest.builder().tableName("table_name").ids(Arrays.asList("1", "2")).build();
            CompletableFuture<SearchResponse> searchResponseCompletableFuture = client.fetch(fetchRequest);
            String responseBody = searchResponseCompletableFuture.get().getBody();

            System.out.println("result: " + responseBody);

        } catch (ExecutionException | InterruptedException e) {
            System.out.println(e.getMessage());
        } catch (TeaException e) {
            System.out.println(e.getMessage());
            Map<String, Object> abc = e.getData();
            System.out.println(com.aliyun.teautil.Common.toJSONString(abc));
        }
    }
}

Java

package com.aliyun.ha3engine.demo;

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

import com.aliyun.ha3engine.vector.Client;
import com.aliyun.ha3engine.vector.models.Config;
import com.aliyun.ha3engine.vector.models.FetchRequest;
import com.aliyun.ha3engine.vector.models.SearchResponse;
import com.aliyun.tea.TeaException;

import org.junit.Before;
import org.junit.Test;

public class Demo {

    /**
     * The engine client of the OpenSearch Vector Search Edition instance. The client supports query operations.
     */
    private Client client;

    @Before
    public void clientInit() throws Exception {

        /*
          Initialize the engine client.
         */
        Config config = new Config();

        // The name of the OpenSearch Vector Search Edition instance. You can view the instance name in the upper-left corner of the Instance Details page. Example: ha-cn-i7*****605.
        config.setInstanceId("ha-cn-i7*****605");

        // The username. You can view the username in the API Endpoint section of the Instance Details page.
        config.setAccessUserName("username");

        // The password. You can modify the password in the API Endpoint section of the Instance Details page.
        config.setAccessPassWord("password");

        // To access the instance by using an internal endpoint, specify the endpoint. To access the instance by using a public endpoint, uncomment the following line:
        config.setEndpoint("ha-cn-i7*****605.public.ha.aliyuncs.com");
        // To access the instance over the Internet, uncomment the following line and specify the HTTP proxy.
//        config.setHttpProxy("http://116.62.XXX.XXX:80");

        client = new Client(config);

    }

    @Test
    public void fetch() throws Exception {
        try {
            FetchRequest request = new FetchRequest();
            request.setTableName("gist");
            request.setIds(Arrays.asList("1", "2"));
            SearchResponse searchResponse = client.fetch(request);
            System.out.println("Result:\n" + searchResponse.getBody());
        } catch (TeaException e) {
            System.out.println(e.getCode());
            System.out.println(e.getMessage());
            Map<String, Object> abc = e.getData();
            System.out.println(com.aliyun.teautil.Common.toJSONString(abc));
        }
    }

}

Python

from alibabacloud_ha3engine_vector.client import Client
from alibabacloud_ha3engine_vector.models import Config
from alibabacloud_ha3engine_vector.models import FetchRequest

config = Config(
        # To access the instance by using an internal endpoint, specify the endpoint.
        endpoint="ha-cn-7mz2ougaw02.ha.aliyuncs.com",
        # The name of the OpenSearch Vector Search Edition instance. You can view the instance name in the upper-left corner of the Instance Details page. Example: ha-cn-i7*****605.
        instance_id="ha-cn-7mz2ougaw02",
        # The username. You can view the username in the API Endpoint section of the Instance Details page.
        access_user_name="user",
        # The password. You can modify the password in the API Endpoint section of the Instance Details page.
        access_pass_word="111111")
client = Client(config)

request = FetchRequest(table_name="gist", ids=["1", "2"])
result = client.fetch(request)

Go

package main

import (
	"fmt"
	"github.com/alibabacloud-go/tea/tea"
	ha3engine "github.com/aliyun/alibabacloud-ha3-go-sdk/client"
)

func main() {

	// Create a Config instance.
	config := &ha3engine.Config{
		// The internal or public endpoint.
		Endpoint: tea.String("<Endpoint>"),
		// The name of the OpenSearch Vector Search Edition instance. You can view the instance name in the upper-left corner of the Instance Details page. Example: ha-cn-i7*****605.
		InstanceId: tea.String("<InstanceId>"),
		// The username. You can view the username in the API Endpoint section of the Instance Details page.
		AccessUserName: tea.String("<AccessUserName>"),
		// The password. You can modify the password in the API Endpoint section of the Instance Details page.
		AccessPassWord: tea.String("<AccessPassWord>"),
	}

	// Initialize a client for sending requests.
	client, _clientErr := ha3engine.NewClient(config)

	// If an error occurs when the system creates the client, _clientErr and an error message are returned.
	if _clientErr != nil {
		fmt.Println(_clientErr)
		return
	}

	fetch(client)
}


/**
 * Primary key-based query
 */
func fetch(client *ha3engine.Client) {

	searchRequestModel := &ha3engine.FetchRequest{}
	searchRequestModel.SetTableName("api")

	// Assign values to the elements of the array.
	ids := make([]*string, 3)
	ids[0] = tea.String("1")
	ids[1] = tea.String("2")
	ids[2] = tea.String("3")
	searchRequestModel.SetIds(ids)

	response, _requestErr := client.Fetch(searchRequestModel)

	// If an error occurs when the system sends the request, _requestErr and an error message are returned.
	if _requestErr != nil {
		fmt.Println(_requestErr)
		return
	}

	// Display the response if no error occurs.
	fmt.Println(response)

}

Prediction query

You can perform prediction queries when you use OpenSearch Vector Search Edition to vectorize text or images for vector-based queries. The following code provides examples on how to use SDKs to perform prediction queries.

Java in asynchronous mode

package com.aliyun.ha3engine;

import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

import com.aliyun.ha3engine.async.AsyncClient;
import com.aliyun.ha3engine.async.models.QueryRequest;
import com.aliyun.ha3engine.async.models.SearchResponse;
import com.aliyun.sdk.ha3engine.async.core.AsyncConfigInfoProvider;
import com.aliyun.tea.TeaException;

import darabonba.core.client.ClientOverrideConfiguration;

/**
 * @author alibaba
 */
public class SearchDoc {

    public static void main(String[] args) throws Exception {
        try {
            // The username and password that are used to access the instance. You can view the username and password in the API Endpoint section of the Instance Details page.
            AsyncConfigInfoProvider provider = AsyncConfigInfoProvider.create("username", "password");

            // Initialize the asynchronous client.
            AsyncClient client = AsyncClient.builder()
                    .credentialsProvider(provider)
                    .overrideConfiguration(
                            ClientOverrideConfiguration.create()
                                    // The public endpoint of the instance. You can view the public endpoint in the Network Information section of the Instance Details page.
                                    .setEndpointOverride("ha-cn-***********.public.ha.aliyuncs.com")
                            .setProtocol("http")
                    ).build();
            QueryRequest queryRequest = QueryRequest.builder()
                    .tableName("table_name") // The name of the table to be queried.
                    .indexName("index_name") // The name of the index to be queried.
                    .topK(10) // The number of results to be returned.
                    .includeVector(true) // Specifies whether to return the vector information in documents.
                    .build();
            CompletableFuture<SearchResponse> responseCompletableFuture = client.query(queryRequest);
            String responseBody = responseCompletableFuture.get().getBody();

            System.out.println("result: " + responseBody);

        } catch (ExecutionException | InterruptedException e) {
            System.out.println(e.getMessage());
        } catch (TeaException e) {
            System.out.println(e.getMessage());
            Map<String, Object> abc = e.getData();
            System.out.println(com.aliyun.teautil.Common.toJSONString(abc));
        }
    }
}

Java

package com.aliyun.ha3engine.demo;

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

import com.aliyun.ha3engine.vector.Client;
import com.aliyun.ha3engine.vector.models.Config;
import com.aliyun.ha3engine.vector.models.QueryRequest;
import com.aliyun.ha3engine.vector.models.SearchResponse;
import com.aliyun.tea.TeaException;

import org.junit.Before;
import org.junit.Test;

public class Demo {

    /**
     * The engine client of the OpenSearch Vector Search Edition instance. The client supports query operations.
     */
    private Client client;

    @Before
    public void clientInit() throws Exception {

        /*
          Initialize the engine client.
         */
        Config config = new Config();

        // The name of the OpenSearch Vector Search Edition instance. You can view the instance name in the upper-left corner of the Instance Details page. Example: ha-cn-i7*****605.
        config.setInstanceId("ha-cn-i7*****605");

        // The username. You can view the username in the API Endpoint section of the Instance Details page.
        config.setAccessUserName("username");

        // The password. You can modify the password in the API Endpoint section of the Instance Details page.
        config.setAccessPassWord("password");

        // To access the instance by using an internal endpoint, specify the endpoint. To access the instance by using a public endpoint, uncomment the following line:
        config.setEndpoint("ha-cn-i7*****605.public.ha.aliyuncs.com");
        // To access the instance over the Internet, uncomment the following line and specify the HTTP proxy.
        //        config.setHttpProxy("http://116.62.XXX.XXX:80");

        client = new Client(config);
    }

    @Test
    public void query() throws Exception {
        try {
            QueryRequest request = new QueryRequest();
            request.setTableName("gist"); // Required. The name of the table to be queried.
            request.setContent("Child"); // Required. The content that you want to query.
            request.setModal("text"); // Required. This parameter is used to vectorize the terms to be queried.
            request.setTopK(100); // Optional. The number of results to be returned.
    request.setSearchParams("{\\\"qc.searcher.scan_ratio\\\":0.01}");
            SearchResponse searchResponse = client.inferenceQuery(request);
            System.out.println("Result:\n" + searchResponse.getBody());
        } catch (TeaException e) {
            System.out.println(e.getCode());
            System.out.println(e.getMessage());
            Map<String, Object> abc = e.getData();
            System.out.println(com.aliyun.teautil.Common.toJSONString(abc));
        }
    }
}

Python

from alibabacloud_ha3engine_vector.client import Client
from alibabacloud_ha3engine_vector.models import Config
from alibabacloud_ha3engine_vector.models import QueryRequest

config = Config(
    # To access the instance by using an internal endpoint, specify the endpoint.
    endpoint="ha-cn-7mz2ougaw02.ha.aliyuncs.com",
    # The name of the OpenSearch Vector Search Edition instance. You can view the instance name in the upper-left corner of the Instance Details page. Example: ha-cn-i7*****605.
    instance_id="ha-cn-7mz2ougaw02",
    # The username. You can view the username in the API Endpoint section of the Instance Details page.
    access_user_name="user",
    # The password. You can modify the password in the API Endpoint section of the Instance Details page.
    access_pass_word="111111")
client = Client(config)

request = QueryRequest(table_name="gist",
                       content="Child",
                       modal="text",
                       search_params="{\\\"qc.searcher.scan_ratio\\\":0.01}",
                       top_k=10)
result = client.inference_query(request)

Go

package main

import (
	"fmt"
	"github.com/alibabacloud-go/tea/tea"
	ha3engine "github.com/aliyun/alibabacloud-ha3-go-sdk/client"
)

func main() {

	// Create a Config instance.
	config := &ha3engine.Config{
		// The internal or public endpoint.
		Endpoint: tea.String("<Endpoint>"),
		// The name of the OpenSearch Vector Search Edition instance. You can view the instance name in the upper-left corner of the Instance Details page. Example: ha-cn-i7*****605.
		InstanceId: tea.String("<InstanceId>"),
		// The username. You can view the username in the API Endpoint section of the Instance Details page.
		AccessUserName: tea.String("<AccessUserName>"),
		// The password. You can modify the password in the API Endpoint section of the Instance Details page.
		AccessPassWord: tea.String("<AccessPassWord>"),
	}

	// Initialize a client for sending requests.
	client, _clientErr := ha3engine.NewClient(config)

	// If an error occurs when the system creates the client, _clientErr and an error message are returned.
	if _clientErr != nil {
		fmt.Println(_clientErr)
		return
	}

	inferenceQuery(client)
}

/**
 * Prediction query
 */
func inferenceQuery(client *ha3engine.Client) {

	searchRequestModel := &ha3engine.QueryRequest{}
	searchRequestModel.SetTableName("api")

	// Create an array of 32-bit floating-point numbers.
	array := make([]*float32, 3)

	// Allocate a memory address to each value of the array and initialize the values.
	value1 := float32(1.23)
	value2 := float32(4.56)
	value3 := float32(7.89)

	// Assign values to the elements of the array.
	array[0] = &value1
	array[1] = &value2
	array[2] = &value3

	searchRequestModel.SetVector(array)

	response, _requestErr := client.InferenceQuery(searchRequestModel)

	// If an error occurs when the system sends the request, _requestErr and an error message are returned.
	if _requestErr != nil {
		fmt.Println(_requestErr)
		return
	}

	// Display the response if no error occurs.
	fmt.Println(response)

}

Parameters:

  • The content parameter in QueryRequest indicates the content that you specify for the query. In text vectorization scenarios, you can specify text as the content to be queried. In image vectorization scenarios, you can specify text or images that are encoded in Base64 as the content to be queried.

  • The modal parameter in QueryRequest indicates the query mode. If you set the parameter to text, the system queries text based on the specified text in text vectorization scenarios, and queries images based on the specified text in image vectorization scenarios.

Batch query

Java in asynchronous mode

package com.aliyun.ha3engine;

import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

import com.aliyun.ha3engine.async.AsyncClient;
import com.aliyun.ha3engine.async.models.MultiQueryRequest;
import com.aliyun.ha3engine.async.models.QueryRequest;
import com.aliyun.ha3engine.async.models.SearchResponse;
import com.aliyun.sdk.ha3engine.async.core.AsyncConfigInfoProvider;
import com.aliyun.tea.TeaException;

import darabonba.core.client.ClientOverrideConfiguration;

/**
 * @author alibaba
 */
public class SearchDoc {

    public static void main(String[] args) throws Exception {
        try {
            // The username and password that are used to access the instance. You can view the username and password in the API Endpoint section of the Instance Details page.
            AsyncConfigInfoProvider provider = AsyncConfigInfoProvider.create("username", "password");

            // Initialize the asynchronous client.
            AsyncClient client = AsyncClient.builder()
                    .credentialsProvider(provider)
                    .overrideConfiguration(
                            ClientOverrideConfiguration.create()
                                    // The public endpoint of the instance. You can view the public endpoint in the Network Information section of the Instance Details page.
                                    .setEndpointOverride("ha-cn-***********.public.ha.aliyuncs.com")
                            .setProtocol("http")
                    ).build();

            QueryRequest queryRequest = QueryRequest.builder()
                    .indexName("content_vec") // The name of the index to be queried.
                    .namespace("150086193") // The namespace of the index to be queried.
                    .vector(Arrays.asList(0.0001575F, 0.00682848F)) // The vector data to be queried.
                    .build();
            MultiQueryRequest multiQueryRequest = MultiQueryRequest.builder()
                    .tableName("hybrid") // The name of the table to be queried.
                    .topK(10) // The number of results to be returned.
                    .outputFields(Arrays.asList("content", "source", "instance_id")) // The fields to be returned.
                    .filter("type='TEXT'") // The filter expression.
                    .order("DESC") // The order in which the returned documents are sorted.
                    .queries(Arrays.asList(queryRequest)).build();
            CompletableFuture<SearchResponse> searchResponseCompletableFuture = client.multiQuery(multiQueryRequest);
            String responseBody = searchResponseCompletableFuture.get().getBody();

            System.out.println("result: " + responseBody);

        } catch (ExecutionException | InterruptedException e) {
            System.out.println(e.getMessage());
        } catch (TeaException e) {
            System.out.println(e.getMessage());
            Map<String, Object> abc = e.getData();
            System.out.println(com.aliyun.teautil.Common.toJSONString(abc));
        }
    }
}

Go

package main

import (
	"fmt"
	"github.com/alibabacloud-go/tea/tea"
	ha3engine "github.com/aliyun/alibabacloud-ha3-go-sdk/client"
)

func main() {

	// Create a Config instance.
	config := &ha3engine.Config{
		// The internal or public endpoint.
		Endpoint: tea.String("<Endpoint>"),
		// The name of the OpenSearch Vector Search Edition instance. You can view the instance name in the upper-left corner of the Instance Details page. Example: ha-cn-i7*****605.
		InstanceId: tea.String("<InstanceId>"),
		// The username. You can view the username in the API Endpoint section of the Instance Details page.
		AccessUserName: tea.String("<AccessUserName>"),
		// The password. You can modify the password in the API Endpoint section of the Instance Details page.
		AccessPassWord: tea.String("<AccessPassWord>"),
	}

	// Initialize a client for sending requests.
	client, _clientErr := ha3engine.NewClient(config)

	// If an error occurs when the system creates the client, _clientErr and an error message are returned.
	if _clientErr != nil {
		fmt.Println(_clientErr)
		return
	}

	multiQuery(client)
}

/**
 * Batch query
 */
func multiQuery(client *ha3engine.Client) {

	query := &ha3engine.QueryRequest{}
	query.SetTableName("api")

	// Create an array of 32-bit floating-point numbers.
	array := make([]*float32, 3)

	// Allocate a memory address to each value of the array and initialize the values.
	value1 := float32(1.23)
	value2 := float32(4.56)
	value3 := float32(7.89)

	// Assign values to the elements of the array.
	array[0] = &value1
	array[1] = &value2
	array[2] = &value3

	query.SetVector(array)

	request := &ha3engine.MultiQueryRequest{}

	request.SetTableName("api")

	querys := make([]*ha3engine.QueryRequest, 3)
	querys[0] = query
	request.SetQueries(querys)
	request.SetTopK(10)
	request.SetIncludeVector(true)
	request.SetOrder("DESC")

	response, _requestErr := client.MultiQuery(request)

	// If an error occurs when the system sends the request, _requestErr and an error message are returned.
	if _requestErr != nil {
		fmt.Println(_requestErr)
		return
	}

	// Display the response if no error occurs.
	fmt.Println(response)

}

Hybrid query by using a single vector

You can perform hybrid queries by using dense vectors and sparse vectors. The following sample code provides examples on how to use SDKs to perform hybrid queries:

import com.aliyun.ha3engine.vector.Client;
import com.aliyun.ha3engine.vector.models.*;
import com.aliyun.tea.TeaException;
import org.junit.Before;
import org.junit.Test;

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

public class Demo {

    /**
     * The engine client of the OpenSearch Vector Search Edition instance. The client supports query operations.
     */
    private Client client;

    @Before
    public void clientInit() throws Exception {

        /*
          Initialize the engine client.
         */
        Config config = new Config();

        // The name of the OpenSearch Vector Search Edition instance. You can view the instance name in the upper-left corner of the Instance Details page. Example: ha-cn-i7*****605.
        config.setInstanceId("ha-cn-***********");

        // The username. You can view the username in the API Endpoint section of the Instance Details page.
        config.setAccessUserName("xxx");

        // The password. You can modify the password in the API Endpoint section of the Instance Details page.
        config.setAccessPassWord("xxx");

        // To access the instance by using an internal endpoint, specify the endpoint. To access the instance by using a public endpoint, uncomment the following line:
        config.setEndpoint("ha-cn-**********.public.ha.aliyuncs.com");
        // To access the instance over the Internet, uncomment the following line and specify the HTTP proxy.
//		config.setHttpProxy("http://120.27.XXX.XX:80");
        client = new Client(config);
    }
    
    @Test
    public void query() throws Exception {
        try {
            QueryRequest queryRequest = new QueryRequest();
            queryRequest.setIndexName("vector"); // The name of the index to be queried. Specify this parameter in SearchRequest or in each query.
            queryRequest.setNamespace("xxx"); // The namespace of the vector data.
            queryRequest.setVector(Arrays.asList(0.0001575F, 0.00682848F)); // The vector data to be queried. The data is of the ARRAY type.

            SparseData sparseData = new SparseData();
            sparseData.setCount(Arrays.asList(2)); // The number of elements in each sparse vector.
            sparseData.setIndices(Arrays.asList(983589459L, 1261855554L)); // The indexes of the elements in ascending order.
            sparseData.setValues(Arrays.asList(0.0001575F, 0.00682848F)); // The values of the elements in the same order as the indexes.

            queryRequest.setSparseData(sparseData);

            SearchResponse searchResponse = client.query(queryRequest);
            System.out.println(searchResponse.getBody());

        } catch (TeaException e) {
            System.out.println(e.getCode());
            System.out.println(e.getMessage());
            Map<String, Object> abc = e.getData();
            System.out.println(com.aliyun.teautil.Common.toJSONString(abc));
        }
    }
}
from alibabacloud_ha3engine_vector.client import Client
from alibabacloud_ha3engine_vector.models import Config
from alibabacloud_ha3engine_vector.models import SparseData
from alibabacloud_ha3engine_vector.models import QueryRequest

config = Config(
    # To access the instance by using an internal endpoint, specify the endpoint.
    endpoint="ha-***",
    # The name of the OpenSearch Vector Search Edition instance. You can view the instance name in the upper-left corner of the Instance Details page. Example: ha-cn-i7*****605.
    instance_id="ha-***",
    # The username. You can view the username in the API Endpoint section of the Instance Details page.
    access_user_name="xxx",
    # The password. You can modify the password in the API Endpoint section of the Instance Details page.
    access_pass_word="xxx")
client = Client(config)
sparseData = SparseData(indices=[101, 203], values=[0.1, 0.5])
request = QueryRequest(table_name="t1",
                       index_name="vec_index",
                       vector=[0.1, 0.2, 0.3, 0.4],
                       sparse_data=sparseData
                       include_vector=True,
                       output_fields=["a", "b"],
                       top_k=10)
result = client.query(request)

Hybrid query by using multiple vectors

You can perform hybrid queries by using dense vectors and sparse vectors. The following sample code provides examples on how to use SDKs to perform hybrid queries:

import com.aliyun.ha3engine.vector.Client;
import com.aliyun.ha3engine.vector.models.*;
import com.aliyun.tea.TeaException;
import org.junit.Before;
import org.junit.Test;

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

public class Demo {

    /**
     * The engine client of the OpenSearch Vector Search Edition instance. The client supports query operations.
     */
    private Client client;

    @Before
    public void clientInit() throws Exception {

        /*
          Initialize the engine client.
         */
        Config config = new Config();

        // The name of the OpenSearch Vector Search Edition instance. You can view the instance name in the upper-left corner of the Instance Details page. Example: ha-cn-i7*****605.
        config.setInstanceId("ha-cn-***********");

        // The username. You can view the username in the API Endpoint section of the Instance Details page.
        config.setAccessUserName("xxx");

        // The password. You can modify the password in the API Endpoint section of the Instance Details page.
        config.setAccessPassWord("xxx");

        // To access the instance by using an internal endpoint, specify the endpoint. To access the instance by using a public endpoint, uncomment the following line:
        config.setEndpoint("ha-cn-**********.public.ha.aliyuncs.com");
        // To access the instance over the Internet, uncomment the following line and specify the HTTP proxy.
//      config.setHttpProxy("http://120.27.XXX.XX:80");

        client = new Client(config);
    }

    @Test
    public void query() throws Exception {
        try {

            MultiQueryRequest multiQueryRequest = new MultiQueryRequest();

            multiQueryRequest.setTableName("main"); // The name of the table to be queried.
            multiQueryRequest.setTopK(50); // The number of results to be returned.
            multiQueryRequest.setOutputFields(Arrays.asList("content", "source", "instance_id")); // The fields to be returned.
            multiQueryRequest.setFilter("type='TEXT'"); // The filter expression.
            multiQueryRequest.setOrder("DESC");

            QueryRequest queryRequest = new QueryRequest();
            queryRequest.setIndexName("vector"); // The name of the index to be queried. Specify this parameter in SearchRequest or in each query.
            queryRequest.setNamespace("xxx"); // The namespace of the vector data.
            queryRequest.setVector(Arrays.asList(0.0001575F, 0.00682848F)); // The vector data to be queried. The data is of the ARRAY type.

            SparseData sparseData = new SparseData();
            sparseData.setCount(Arrays.asList(2)); // The number of elements in each sparse vector.
            sparseData.setIndices(Arrays.asList(983589459L, 1261855554L)); // The indexes of the elements in ascending order.
            sparseData.setValues(Arrays.asList(0.0001575F, 0.00682848F)); // The values of the elements in the same order as the indexes.

            queryRequest.setSparseData(sparseData);
            multiQueryRequest.setQueries(Arrays.asList(queryRequest));

            SearchResponse searchResponse = client.multiQuery(multiQueryRequest);
            System.out.println(searchResponse.getBody());

        } catch (TeaException e) {
            System.out.println(e.getCode());
            System.out.println(e.getMessage());
            Map<String, Object> abc = e.getData();
            System.out.println(com.aliyun.teautil.Common.toJSONString(abc));
        }
    }
}
from alibabacloud_ha3engine_vector.client import Client
from alibabacloud_ha3engine_vector.models import Config
from alibabacloud_ha3engine_vector.models import SparseData
from alibabacloud_ha3engine_vector.models import QueryRequest
from alibabacloud_ha3engine_vector.models import MultiQueryRequest

config = Config(
        # To access the instance by using an internal endpoint, specify the endpoint.
        endpoint="ha-***",
        # The name of the OpenSearch Vector Search Edition instance. You can view the instance name in the upper-left corner of the Instance Details page. Example: ha-cn-i7*****605.
        instance_id="ha-***",
        # The username. You can view the username in the API Endpoint section of the Instance Details page.
        access_user_name="xxx",
        # The password. You can modify the password in the API Endpoint section of the Instance Details page.
        access_pass_word="xxx")
client = Client(config)
sd1 = SparseData(indices=[101, 203], values=[0.1, 0.5])
sd2 = SparseData(indices=[200, 405, 502], values=[0.9, 0.5, 0.75])
q1 = QueryRequest(vector=[0.1, 0.2, 0.3], namespace="space_a", sparse_data=sd1)
q2 = QueryRequest(vector=[0.4, 0.5, 0.6], namespace="space_b", sparse_data=sd2)
request = MultiQueryRequest(table_name = "gist", 
                                 queries=[q1, q2], 
                                 top_k=3, 
                                 include_vector=True)
result = client.multi_query(request)
Important

To perform queries based on multiple vectors, make sure that the vectors are of the same type. For example, you can perform queries based on multiple dense vectors or dense-sparse vectors.

Note

  • For more information about the response to a request, see the Response parameters section of the "Vector-based query" topic.

  • Do not run the go get github.com/aliyun/alibabacloud-ha3-go-sdk command to pull dependencies. The SDK dependencies for OpenSearch Vector Search Edition and OpenSearch Retrieval Engine Edition are classified into the same tag in GitHub. You must specify the corresponding edition based on the instance edition when you pull dependencies.