すべてのプロダクト
Search
ドキュメントセンター

OpenSearch:OpenSearch SDK の使用例 - 検索機能を実装するためのデモコード

最終更新日:Apr 09, 2025

このトピックでは、OpenSearch SDK を使用して Q&A テストを実行する方法について説明します。

環境変数の設定

ALIBABA_CLOUD_ACCESS_KEY_ID および ALIBABA_CLOUD_ACCESS_KEY_SECRET 環境変数を設定します。

重要
  • Alibaba Cloud アカウントの AccessKey ペアを使用すると、すべての API 操作にアクセスできます。 API 操作の呼び出しや日常的な O&M の実行には、Resource Access Management (RAM) ユーザーを使用することをお勧めします。 RAM ユーザーの使用方法については、「RAM ユーザーの作成」をご参照ください。

  • AccessKey ペアの作成方法については、「AccessKey ペアの作成」をご参照ください。

  • RAM ユーザーの AccessKey ペアを使用する場合は、Alibaba Cloud アカウントを使用して、AliyunServiceRoleForOpenSearch ロールに必要な権限が付与されていることを確認してください。 詳細については、「AliyunServiceRoleForOpenSearch」および「アクセス認証ルール」をご参照ください。

  • プロジェクトコードなど、他の人が簡単にアクセスできる資料に AccessKey ペアを含めないことをお勧めします。 そうしないと、AccessKey ペアが漏洩し、アカウント内のリソースが安全でなくなる可能性があります。

  • Linux および macOS

    次のコマンドを実行します。 <access_key_id> および <access_key_secret> を、使用する RAM ユーザーの AccessKey ID と AccessKey シークレットに置き換えます。

    export ALIBABA_CLOUD_ACCESS_KEY_ID=<access_key_id> 
    export ALIBABA_CLOUD_ACCESS_KEY_SECRET=<access_key_secret>
  • Windows

    1. 環境変数ファイルを作成し、ALIBABA_CLOUD_ACCESS_KEY_ID および ALIBABA_CLOUD_ACCESS_KEY_SECRET 環境変数をファイルに追加してから、環境変数に AccessKey ID と AccessKey シークレットを設定します。

    2. AccessKey ペアを有効にするには、Windows を再起動します。

依存関係

OpenSearch SDK を使用してファイルをアップロードするには、次の依存関係を指定する必要があります。

<dependency>
    <groupId>com.aliyun.opensearch</groupId>
    <artifactId>aliyun-sdk-opensearch</artifactId>
    <version>6.0.0</version>
</dependency>
pip install alibabacloud_tea_util 
pip install alibabacloud_opensearch_util
pip install alibabacloud_credentials
V3.4.1 (2021-05-11)
Download URL: https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20230719/mxik/opensearch-sdk-php-release-v3.4.1.zip

デモコード

BaseRequest については、「Python クライアントのサンプルコード」をご参照ください。

package com.aliyun.opensearch;

import com.aliyun.opensearch.OpenSearchClient;
import com.aliyun.opensearch.sdk.generated.OpenSearch;
import com.aliyun.opensearch.sdk.generated.commons.OpenSearchClientException;
import com.aliyun.opensearch.sdk.generated.commons.OpenSearchException;
import com.aliyun.opensearch.sdk.generated.commons.OpenSearchResult;

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

public class LLMSearch {
    private static String appName = "アプリケーション名を置き換えてください"; // アプリケーション名を置き換えてください
    private static String host = "API エンドポイントを置き換えてください"; // API エンドポイントを置き換えてください
    private static String path = "/apps/AppName/actions/knowledge-search";

    public static void main(String[] args) {
      // ユーザー識別情報
      // AccessKey ID と AccessKey Secret を環境変数から取得します。サンプルコードを実行する前に、環境変数を設定する必要があります。
      String accesskey = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
      String secret = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
        //ApiReadTimeOut
        OpenSearch openSearch = new OpenSearch(accesskey, secret, host);
        openSearch.setTimeout(90000);

        OpenSearchClient openSearchClient = new OpenSearchClient(openSearch);

        Map<String, String> params = new HashMap<String, String>() {{
            put("format", "full_json");
            put("_POST_BODY", "{\"question\":{\"text\":\"How to charge\",\"type\":\"TEXT\",\"session\":\"\"},\"options\":{\"retrieve\":{\"doc\":{\"filter\":\"\",\"top_n\":5,\"sf\":\"\",\"dense_weight\":\"0.7\",\"formula\":\"\",\"operator\":\"AND\"},\"entry\":{\"sf\":\"\"},\"image\":{\"sf\":\"\",\"dense_weight\":\"0.7\"},\"qp\":{\"query_extend\":false,\"query_extend_num\":5},\"return_hits\":false,\"rerank\":{\"enable\":true,\"model\":\"ops-bge-reranker-larger\"}},\"chat\":{\"stream\":true,\"prompt_config\":{\"attitude\":\"normal\",\"rule\":\"detailed\",\"noanswer\":\"sorry\",\"language\":\"Chinese\",\"role\":false,\"role_name\":\"AI Assistant\",\"out_format\":\"text\"},\"agent\":{\"tools\":[]},\"csi_level\":\"strict\",\"history_max\":\"\",\"link\":\"false\",\"model\":\"qwen-plus\",\"model_generation\":\"\"}}}");

        }};
      	try {
            OpenSearchResult openSearchResult = openSearchClient
            .callAndDecodeResult(path, params, "POST");
            System.out.println("RequestID=" + openSearchResult.getTraceInfo().getRequestId());
            System.out.println(openSearchResult.getResult());
        } catch (
            OpenSearchException e) {
            System.out.println("RequestID=" + e.getRequestId());
            System.out.println("ErrorCode=" + e.getCode());
            System.out.println("ErrorMessage=" + e.getMessage());
        } catch (
            OpenSearchClientException e) {
            System.out.println("ErrorMessage=" + e.getMessage());
        }
    }
}
# -*- coding: utf-8 -*-

import time, os
from typing import Dict, Any

from Tea.exceptions import TeaException
from Tea.request import TeaRequest
from alibabacloud_tea_util import models as util_models
from BaseRequest import Config, Client


class LLMSearch:
    def __init__(self, config: Config):
        self.Clients = Client(config=config)
        self.runtime = util_models.RuntimeOptions(
            connect_timeout=10000,
            read_timeout=90000,
            autoretry=False,
            ignore_ssl=False,
            max_idle_conns=50,
            max_attempts=3
        )
        self.header = {}


    def searchDoc(self, app_name: str,body:Dict, query_params: dict={}) -> Dict[str, Any]:
        try:
            response = self.Clients._request(method="POST", pathname=f'/v3/openapi/apps/{app_name}/actions/knowledge-search',
                                             query=query_params, headers=self.header, body=body, runtime=self.runtime)
            return response
        except TeaException as e:
            print(e)


if __name__ == "__main__":
    # 統合リクエストエンドポイントを http:// プレフィックスなしで指定します
    endpoint = "<endpoint>"

    # プロトコルを指定します。有効な値: HTTPS/HTTP
    endpoint_protocol = "HTTP"

    # ユーザー識別情報
    # AccessKey ID と AccessKey Secret を環境変数から取得します。
    # サンプルコードを実行する前に、環境変数を設定する必要があります。詳細については、このトピックの「環境変数の設定」セクションを参照してください。
    access_key_id = os.environ.get("ALIBABA_CLOUD_ACCESS_KEY_ID")
    access_key_secret = os.environ.get("ALIBABA_CLOUD_ACCESS_KEY_SECRET")

    # 認証タイプを指定します。有効な値: sts/access_key。デフォルト値は access_key です。 sts を使用して RAM-STS 認証を設定できます。
    # 有効な値: sts または access_key
    auth_type = "access_key"

    # RAM-STS 認証を使用する場合は、security_token パラメーターを指定します。 Alibaba Cloud AssumeRole を使用して、関連する STS 認証構造を取得できます。
    security_token =  "<security_token>"

    # 共通のリクエスト情報を指定します。
    # type パラメーターと security_token パラメーターは、SDK を RAM ユーザーとして使用する場
<?php
require_once($path . "/OpenSearch/Autoloader/Autoloader.php");

use OpenSearch\Client\OpenSearchClient;

// ユーザー識別情報
// AccessKey ID と AccessKey Secret を環境変数から取得します。
// サンプルコードを実行する前に、環境変数を設定する必要があります。詳細については、このトピックの「環境変数を設定する」セクションをご参照ください。
// 対応するアクセスキー ID に置き換えます
$accessKeyId = getenv('ALIBABA_CLOUD_ACCESS_KEY_ID');
// 対応するアクセスシークレットに置き換えます
$secret = getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET');
$endPoint = '<エンドポイントに置き換えてください>';
$appName = '<アプリケーション名に置き換えてください>';
$options = array('timeout' => 90);
$requestBody = "{\"question\":{\"text\":\"Based on the survey of various types of typical sites\",\"type\":\"TEXT\"}}";

$client = new OpenSearchClient($accessKeyId, $secret, $endPoint, $options);

$uri = "/apps/{$appName}/actions/knowledge-search";

try{
    $ret = $client->post($uri, $requestBody);
    print_r(json_decode($ret->result, true));
}catch (\Throwable $e) {
    print_r($e);
}
説明

POST_BODY の他のパラメーターの詳細については、「SearchKnowledge」をご参照ください。

Java SDK ストリーミング出力 のサンプルコード

サンプルリクエスト

  • AccessKey の使用

    説明

    次のサンプルでは、Java SDK バージョン 6.0.0 以降が必要です。

    package org.example;
    
    import com.aliyun.opensearch.OpenSearchClient;
    import com.aliyun.opensearch.sdk.dependencies.org.apache.http.HttpResponse;
    import com.aliyun.opensearch.sdk.generated.OpenSearch;
    import com.aliyun.opensearch.sdk.generated.commons.OpenSearchClientException;
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.nio.charset.StandardCharsets;
    import java.util.HashMap;
    import java.util.Map;
    
    public class Main {
        private static String host = "Replace with your access address"; // アクセスアドレスに置き換えてください
    
        public static void main(String[] args) {
          // Obtain the AccessKey ID and AccessKey Secret from environment variables. You must configure the environment variables before running the sample code. // 環境変数から AccessKey ID と AccessKey Secret を取得します。サンプルコードを実行する前に、環境変数を設定する必要があります。
            String accesskey = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
            String secret = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
            OpenSearch openSearch = new OpenSearch(accesskey, secret, host);
            openSearch.setTimeout(90000);
            OpenSearchClient openSearchClient = new OpenSearchClient(openSearch);
            Map<String, String> params = new HashMap<String, String>() {{
                put("_POST_BODY", "{\"question\": {\"text\": \"Beijing\",\"type\": \"TEXT\"},\"options\": {\"chat\": {\"stream\": true}}}");
            }};
    
            String path = "/apps/AppName/actions/knowledge-search";
            try {
                HttpResponse httpResponse = openSearchClient
                        .callForHttpResponse(path, params, "POST");
                InputStream responseBodyStream  = httpResponse.getEntity().getContent();
                BufferedReader br = new BufferedReader(new InputStreamReader(responseBodyStream, StandardCharsets.UTF_8));
                String line;
                while ((line = br.readLine()) != null) {
                    System.out.println(line);
                }
    
                br.close();
                // The request is received. // リクエストが受信されました。
                openSearchClient.getHttpClientManager().getClientTracer().success(httpResponse, "");
            } catch (OpenSearchClientException e) {
                System.out.println("ErrorMessage=" + e.getMessage());
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

  • API Key の使用

    説明

    Java SDK バージョン 6.0.2 以降が必要です。

    package org.example;
    
    import com.aliyun.opensearch.OpenSearchClient;
    import com.aliyun.opensearch.sdk.dependencies.org.apache.http.HttpResponse;
    import com.aliyun.opensearch.sdk.generated.OpenSearch;
    import com.aliyun.opensearch.sdk.generated.commons.OpenSearchClientException;
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.nio.charset.StandardCharsets;
    import java.util.HashMap;
    import java.util.Map;
    
    public class Main {
        private static String host = "Replace with your access address"; // アクセスアドレスに置き換えてください
    
        public static void main(String[] args) {
            // Access using API Key, SDK version must be 6.0.2 or later // API Key を使用したアクセス、SDK バージョンは 6.0.2 以降である必要があります
            OpenSearch openSearch = new OpenSearch();
            openSearch.setBearerToken("OS-xxxx");
            openSearch.setHost(host);
            openSearch.setTimeout(90000);
            OpenSearchClient openSearchClient = new OpenSearchClient(openSearch);
            Map<String, String> params = new HashMap<String, String>() {{
                put("_POST_BODY", "{\"question\": {\"text\": \"Beijing\",\"type\": \"TEXT\"},\"options\": {\"chat\": {\"stream\": true}}}");
            }};
    
            String path = "/apps/AppName/actions/knowledge-search";
            try {
                HttpResponse httpResponse = openSearchClient
                        .callForHttpResponse(path, params, "POST");
                InputStream responseBodyStream  = httpResponse.getEntity().getContent();
                BufferedReader br = new BufferedReader(new InputStreamReader(responseBodyStream, StandardCharsets.UTF_8));
                String line;
                while ((line = br.readLine()) != null) {
                    System.out.println(line);
                }
    
                br.close();
                // The request is received. // リクエストが受信されました。
                openSearchClient.getHttpClientManager().getClientTracer().success(httpResponse, "");
            } catch (OpenSearchClientException e) {
                System.out.println("ErrorMessage=" + e.getMessage());
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

サンプル出力

data:{"request_id":"AF429C69-2D36-4328-A9BA-5ECDEC716176","status":"OK","latency":391.178295,"result":{"data":[{"answer":"Beijing","type":"TEXT"}]}}

data:{"request_id":"AF429C69-2D36-4328-A9BA-5ECDEC716176","status":"OK","latency":409.279769,"result":{"data":[{"answer":"Beijing is in China","type":"TEXT"}]}}

data:{"request_id":"AF429C69-2D36-4328-A9BA-5ECDEC716176","status":"OK","latency":429.260018,"result":{"data":[{"answer":"Beijing is the","type":"TEXT"}]}}

data:{"request_id":"AF429C69-2D36-4328-A9BA-5ECDEC716176","status":"OK","latency":447.107968,"result":{"data":[{"answer":"Beijing is the capital of China","type":"TEXT"}]}}

data:{"request_id":"AF429C69-2D36-4328-A9BA-5ECDEC716176","status":"OK","latency":465.897194,"result":{"data":[{"answer":"Beijing is the capital of China,","type":"TEXT"}]}}

data:{"request_id":"AF429C69-2D36-4328-A9BA-5ECDEC716176","status":"OK","latency":485.54058,"result":{"data":[{"answer":"Beijing is the capital of China, with","type":"TEXT"}]}}

data:{"request_id":"AF429C69-2D36-4328-A9BA-5ECDEC716176","status":"OK","latency":504.273681,"result":{"data":[{"answer":"Beijing is the capital of China, with a long","type":"TEXT"}]}}

data:{"request_id":"AF429C69-2D36-4328-A9BA-5ECDEC716176","status":"OK","latency":523.287943,"result":{"data":[{"answer":"Beijing is the capital of China, with a long history","type":"TEXT"}]}}

data:{"request_id":"AF429C69-2D36-4328-A9BA-5ECDEC716176","status":"OK","latency":542.027658,"result":{"data":[{"answer":"Beijing is the capital of China, with a long history.","type":"TEXT"}]}}

data:{"request_id":"AF429C69-2D36-4328-A9BA-5ECDEC716176","status":"OK","latency":559.790625,"result":{"data":[{"answer":"Beijing is the capital of China, with a long history.","type":"TEXT"}]}}

data:{"request_id":"AF429C69-2D36-4328-A9BA-5ECDEC716176","status":"OK","latency":689.980221,"result":{"data":[{"answer":"Beijing is the capital of China, with a long history.","type":"TEXT","reference":[{"tokenNum":12,"id":"6004483b75f98deb48198e3543a90c0c","title":"Beijing.txt"},{"tokenNum":607,"id":"770f7cb52fec7afb1be65d637063a8cb","title":"Leading New China, Striving for a New Era.docx"}]}]}}

data:[done]