Send a basic search request to OpenSearch Industry Algorithm Edition using the SDK for C#.
Prerequisites
Before you begin, ensure that you have:
An OpenSearch app. Note the app name — it is used in the request path.
The endpoint for your OpenSearch instance. Get it from the OpenSearch console.
An AccessKey pair with permission to call the OpenSearch API. Use a Resource Access Management (RAM) user rather than your Alibaba Cloud root account. For details, see Create a RAM user and Access authorization rules. Make sure that the required permissions are granted to the AliyunServiceRoleForOpenSearch role by using your Alibaba Cloud account. For more information, see AliyunServiceRoleForOpenSearch.
Never embed your AccessKey pair directly in code or commit it to source control. Always read credentials from environment variables or a secrets manager.
Set up credentials
Set the following environment variables before running the sample.
Linux and macOS
export ALIBABA_CLOUD_ACCESS_KEY_ID=<access_key_id>
export ALIBABA_CLOUD_ACCESS_KEY_SECRET=<access_key_secret>Replace <access_key_id> and <access_key_secret> with your RAM user's AccessKey ID and AccessKey secret.
Windows
Add
ALIBABA_CLOUD_ACCESS_KEY_IDandALIBABA_CLOUD_ACCESS_KEY_SECRETto your system environment variables and set them to your AccessKey ID and AccessKey secret.Restart Windows for the changes to take effect.
Install dependencies
Download the following packages from NuGet:
dotnet add package AlibabaCloud.TeaUtil --version 0.1.5
dotnet add package AlibabaCloud.OpenSearchUtil --version 1.0.2
dotnet add package Aliyun.Credentials --version 1.2.1
dotnet add package Tea --version 0.4.0| Package | Role |
|---|---|
AlibabaCloud.TeaUtil | Shared utilities (runtime options, serialization) |
AlibabaCloud.OpenSearchUtil | OpenSearch-specific client helpers |
Aliyun.Credentials | Credential providers (AccessKey, STS) |
Tea | Base HTTP transport layer used by Alibaba Cloud SDKs |
Send a search request
The sample below initializes the OpenSearch client and sends a GET request to the search API.
using System;
using System.Collections.Generic;
using AlibabaCloud.TeaUtil.Models;
using Tea;
namespace ConsoleApp
{
internal class Program
{
// Sends a search request to /v3/openapi/apps/{appName}/search.
// Returns the raw response as a dictionary.
public static Dictionary<string, object> searchDoc(
Client opensearchClient,
string appName,
Dictionary<string, object> queryParams,
Dictionary<string, string> header,
RuntimeOptions runTime)
{
string pathName = "/v3/openapi/apps/" + appName + "/search";
try
{
return opensearchClient._request("GET", pathName, queryParams, header, null, runTime);
}
catch (TeaException e)
{
Console.WriteLine(e);
throw;
}
}
private static void Main(string[] args)
{
// Configure connection behavior.
var runtime = new RuntimeOptions
{
ConnectTimeout = 5000, // 5 seconds
ReadTimeout = 10000, // 10 seconds
MaxAttempts = 0,
Autoretry = false,
IgnoreSSL = false,
MaxIdleConns = 50
};
var config = new Config
{
// Get the endpoint from the OpenSearch console.
Endpoint = "opensearch-cn-hangzhou.aliyuncs.com",
// Use HTTPS (recommended). HTTP is also supported.
Protocol = "HTTPS",
// Read credentials from environment variables set in "Set up credentials".
AccessKeyId = System.Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"),
AccessKeySecret = System.Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"),
// Authentication type. Use "access_key" for AccessKey-based auth,
// or "sts" for RAM + Security Token Service (STS) authentication.
Type = "access_key",
// Required only when Type is "sts". Get a token by calling the AssumeRole API.
SecurityToken = "",
};
// Initialize the OpenSearch client.
var openSearch = new Client(config);
// Replace "appName" with the name of your OpenSearch app.
var appName = "appName";
// Add any custom HTTP headers here, or leave the dictionary empty.
var header = new Dictionary<string, string>();
// Build the query string.
//
// config clause:
// start:0 -- return results beginning at offset 0 (first page)
// hit:10 -- return up to 10 results
// format:fulljson -- return the full JSON response (also supports "json")
//
// query clause:
// (default:"Search" AND default:"OpenSearch") OR (default:"search engine" AND default:"policy")
// Searches the default field for documents matching either term combination.
var docQuery = new Dictionary<string, object>
{
{
"query",
"config=start:0,hit:10,format:fulljson&&query=(default:\"Search\" AND default:\"OpenSearch\") OR (default:\"search engine\" AND default:\"policy\")"
},
{ "second_rank_name", "att" },
{ "first_rank_name", "sdfrsdfs" },
{ "fetch", "qp:profile" },
{ "fetch_fields", "title" } // Return only the title field
};
try
{
Dictionary<string, object> result = searchDoc(openSearch, appName, docQuery, header, runtime);
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
}
}What's next
Initiate search requests — full reference for query syntax, ranking profiles, and response fields.
AliyunServiceRoleForOpenSearch — service role permissions required for OpenSearch operations.
Create an AccessKey pair — create the AccessKey pair used to authenticate API calls.