Statistical syntax of the vector engine

更新时间:
复制 MD 格式

Use the vector engine's statistical syntax to run aggregate queries and statistical analysis on table data. Configure statistical functions (such as max, min, and avg) and grouping fields to perform multi-dimensional analysis across any numeric field in a table.

Supported statistical functions

FunctionDescription
maxReturns the maximum value of a field
minReturns the minimum value of a field
avgReturns the average value of a field
The functions listed above are not exhaustive. Additional statistical functions may be supported. Test with your specific use case.

Prerequisites

Before you begin, ensure that you have:

  • An OpenSearch Vector Search Edition instance

  • The instance name from the upper-left corner of the Instance Details page

  • The API endpoint, username, and password from the API Endpoint section of the Instance Details page

Request parameters

Each aggregate request accepts the following parameters:

ParameterTypeDescription
tableName / table_namestringThe name of the table to query
groupKeys / group_keyslist\<string\>The fields to group results by
aggFuncs / agg_funcslist\<AggFuncDesc\>One or more statistical functions to apply
orderBy / order_bylist\<OrderByDesc\>(Optional) Sort configuration for grouped results.

Each AggFuncDesc entry specifies:

FieldDescriptionExample
funcThe name of the statistical function"max"
argsThe parameters for the statistical function["count"]

Each OrderByDesc entry specifies:

FieldDescriptionExample
fieldThe field to sort by"age"
directionThe sorting method"desc"

Java

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

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

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

public class AggregateService {

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

    @Before
    public void clientInit() throws Exception {
        /*
          Initialize the engine client.
         */
        Config config = new Config();

        // The name of the 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");
        // The API endpoint of the instance. You can view the API endpoint in the API Endpoint section of the Instance Details page.
        config.setEndpoint("ha-cn-i7*****605.public.ha.aliyuncs.com");

        client = new Client(config);
    }

    @Test
    public void aggregate() throws Exception {
        try {
            AggregateRequest request = new AggregateRequest();
            request.setTableName("test1");// The name of the table whose data you want to perform statistical analysis.
            request.setGroupKeys(Arrays.asList("count"));// The fields for grouping statistics.
            List<AggFuncDesc> aggFuncDescList = new ArrayList<>();// The statistical functions.
            AggFuncDesc aggFuncDesc = new AggFuncDesc();
            aggFuncDesc.setFunc("max");// The name of the statistical function.
            aggFuncDesc.setArgs(Arrays.asList("count"));// The parameters for the statistical function.
            aggFuncDescList.add(aggFuncDesc);
            request.setAggFuncs(aggFuncDescList);

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

Python

from alibabacloud_ha3engine_vector.client import Client
from alibabacloud_ha3engine_vector.models import Config, AggregateRequest, AggFuncDesc

config = Config(
    # The API endpoint of the instance. You can view the API endpoint in the API Endpoint section of the Instance Details page.
    endpoint="http://ha-cn-i7*****605.public.ha.aliyuncs.com",
    # The username. You can view the username in the API Endpoint section of the Instance Details page.
    access_user_name="username",
    # The password. You can modify the password in the API Endpoint section of the Instance Details page.
    access_pass_word="password",
    runtime_options=runtime_options)
client = Client(config)

def aggregate():
    agg_func = AggFuncDesc(func="max",
                           args=["count"])
    agg_funcs = [agg_func]
    request = AggregateRequest(table_name="test1",
                               group_keys=["count"],
                               agg_funcs=agg_funcs)
    result = client.aggregate(request)
    print(result.body)

if __name__ == "__main__":
    aggregate()

Go

package main

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

func main() {

	// Create a client instance for sending requests.
	config := &ha3engine.Config{
		// The API endpoint of the instance. You can view the API endpoint in the API Endpoint section of the Instance Details page.
		Endpoint: tea.String("ha-cn-i7*****605.public.ha.aliyuncs.com"),
		// The username. You can view the username in the API Endpoint section of the Instance Details page.
		AccessUserName: tea.String("username"),
		// The password. You can modify the password in the API Endpoint section of the Instance Details page.
		AccessPassWord: tea.String("password"),
		RuntimeOptions: &service.RuntimeOptions{
			KeepAlive:    tea.Bool(true),
			MaxIdleConns: tea.Int(1000),
			ReadTimeout:  tea.Int(1000),
		},
	}

	// 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
	}

	aggregate(client)
}
func aggregate(client *ha3engine.Client) {

	request := &ha3engine.AggregateRequest{}
	request.SetTableName("test1")

	groupKeys := make([]*string, 1)
	groupKeys[0] = tea.String("count")
	request.SetGroupKeys(groupKeys)

	aggFuncDescs := make([]*ha3engine.AggFuncDesc, 1)
	args := make([]*string, 1)
	args[0] = tea.String("count")
	aggFuncDescs[0] = &ha3engine.AggFuncDesc{
		Func: tea.String("max"),
		Args: args,
	}
	request.SetAggFuncs(aggFuncDescs)
	response, _requestErr := client.Aggregate(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)
}

Java in asynchronous mode

The async client returns a CompletableFuture<SearchResponse> and supports an additional orderBy parameter to sort grouped results. Set direction to asc (ascending) or desc (descending).

import com.aliyun.ha3engine.async.AsyncClient;
import com.aliyun.ha3engine.async.models.AggFuncDesc;
import com.aliyun.ha3engine.async.models.AggregateRequest;
import com.aliyun.ha3engine.async.models.OrderByDesc;
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;
import org.junit.Before;
import org.junit.Test;

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

public class AggregateService {

    /**
     * The engine client of the OpenSearch Vector Search Edition instance.
     */
    private AsyncClient client;

    @Before
    public void clientInit() {
        // 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.
        client = AsyncClient.builder()
                .credentialsProvider(provider)
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                .setEndpointOverride("ha-cn-i7*****605.public.ha.aliyuncs.com")
                                .setProtocol("http")
                ).build();
    }

    @Test
    public void aggregate() {
        try {
            AggregateRequest request = AggregateRequest.builder()
                    .tableName("test1")// The name of the table to be queried.
                    .aggFuncs(Arrays.asList(
                            AggFuncDesc.builder()
                                    .func("max")// The name of the statistical function.
                                    .args(Arrays.asList("age"))// The statistical field.
                                    .build()
                    ))// The statistical function.
                    .groupKeys(Arrays.asList("age"))// The field for grouping statistics.
                    .orderBy(Arrays.asList(
                            OrderByDesc.builder()
                                    .field("age")// The sorting field.
                                    .direction("desc")// The sorting method.
                                    .build()
                    ))// The sorting field.
                    .build();

            CompletableFuture<SearchResponse> responseCompletableFuture = client.aggregate(request);
            String responseBody = responseCompletableFuture.get().getBody();

            System.out.println("aggregate result: " + responseBody);
        } catch (ExecutionException | InterruptedException e) {
            System.out.println(e.getMessage());
        } catch (TeaException e) {
            System.out.println(e.getCode());
            System.out.println(e.getMessage());
            Map<String, Object> exceptionData = e.getData();
            System.out.println(com.aliyun.teautil.Common.toJSONString(exceptionData));
        }
    }
}