This page provides a Go code example for sending a search request to OpenSearch High-performance Search Edition. The example covers client initialization, query construction, result summarization with keyword highlighting, and basic error handling.
Prerequisites
Before you begin, ensure that you have:
An OpenSearch High-performance Search Edition application
A RAM user with the
AliyunServiceRoleForOpenSearchrole and the required permissions. See AliyunServiceRoleForOpenSearch and Access authorization rulesAn AccessKey pair for the RAM user. See Create an AccessKey pair
Use a RAM user instead of your Alibaba Cloud account to call API operations. The AccessKey pair of an Alibaba Cloud account has unrestricted access to all resources. For information about creating a RAM user, see Create a RAM user.
Set environment variables
Store your AccessKey pair in environment variables instead of hardcoding credentials in your code.
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 the AccessKey ID and AccessKey secret of your RAM user.
Windows
Create an environment variable file and add
ALIBABA_CLOUD_ACCESS_KEY_IDandALIBABA_CLOUD_ACCESS_KEY_SECRETwith their corresponding values.Restart Windows for the changes to take effect.
Sample code
The example initializes a client, builds a search request with first-phase ranking, second-phase ranking, and summary highlighting, then sends a GET request to /v3/openapi/apps/{appName}/search.
// This file is auto-generated, don't edit it. Thanks.
package main
import (
"fmt"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/alibabacloud-go/tea/tea"
opensearch "main/client"
)
func main() {
// Initialize the client.
// Endpoint: the OpenSearch API endpoint for your region.
// AccessKeyId and AccessKeySecret: read from environment variables set in the previous step.
config := &opensearch.Config{
Endpoint: tea.String("<Endpoint>"),
AccessKeyId: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")),
AccessKeySecret: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")),
}
client, _clientErr := opensearch.NewClient(config)
if _clientErr != nil {
fmt.Println(_clientErr)
return
}
// Build request parameters.
// query: starts at offset 0, returns up to 50 hits in fulljson format, searches the default field for <words>.
// first_rank_name: the first-phase ranking profile to apply.
// second_rank_name: the second-phase ranking profile to apply.
// summary: highlights matched keywords in the description field using <abc>...</abc> tags,
// with a 50-character snippet and ellipsis truncation.
requestParams := map[string]interface{}{
"query": "config=start:0,hit:50,format:fulljson&&query=default:'<words>'",
"first_rank_name": "<rank_name>",
"second_rank_name": "<rank_name>",
"summary": "summary_field:description,summary_ellipsis:...,summary_snipped:1,summary_len:50,summary_element_prefix:<abc>,summary_element_postfix:</abc>",
}
// Configure connection pool and timeout settings.
runtime := &util.RuntimeOptions{
ConnectTimeout: tea.Int(5000),
ReadTimeout: tea.Int(10000),
Autoretry: tea.Bool(false),
IgnoreSSL: tea.Bool(false),
MaxIdleConns: tea.Int(50),
}
// appName: the name or version of the application to query.
appName := "<appName>"
response, _requestErr := client.Request(
tea.String("GET"),
tea.String("/v3/openapi/apps/"+appName+"/search"),
requestParams,
nil,
nil,
runtime)
if _requestErr != nil {
fmt.Println(_requestErr)
return
}
fmt.Println(response)
}Replace the following placeholders before running the code:
| Placeholder | Description |
|---|---|
<Endpoint> | OpenSearch API endpoint for your region |
<words> | The search query term |
<rank_name> | Name of the ranking profile configured in your application |
<appName> | Name or version of your OpenSearch application |
Key parameters
Query syntax
The query parameter uses OpenSearch query syntax. The example configures:
| Sub-parameter | Value | Description |
|---|---|---|
start | 0 | Offset of the first hit to return |
hit | 50 | Maximum number of hits to return |
format | fulljson | Response format |
query | default:'<words>' | Searches the default field for the specified term |
Summary highlighting
The summary parameter highlights matched keywords in the response. The example configures:
| Sub-parameter | Value | Description |
|---|---|---|
summary_field | description | Field to generate the highlighted snippet from |
summary_len | 50 | Maximum character length of the snippet |
summary_ellipsis | ... | String appended when the snippet is truncated |
summary_snipped | 1 | Number of snippets to return per hit |
summary_element_prefix | <abc> | Opening tag wrapping the matched keyword |
summary_element_postfix | </abc> | Closing tag wrapping the matched keyword |
With this configuration, matched keywords in the description field appear as <abc>keyword</abc> in the response. Render these tags as your application requires — for example, replace <abc> with <mark> to apply browser-native highlighting.
Runtime options
| Parameter | Value | Description |
|---|---|---|
ConnectTimeout | 5000 | Connection timeout in milliseconds |
ReadTimeout | 10000 | Read timeout in milliseconds |
Autoretry | false | Whether to retry failed requests automatically |
IgnoreSSL | false | Whether to skip SSL certificate verification |
MaxIdleConns | 50 | Maximum number of idle connections in the connection pool |
Next steps
Customize the
queryparameter to filter by specific fields or apply Boolean logic.Configure ranking profiles (
first_rank_name,second_rank_name) in the OpenSearch console to improve result relevance.Adjust
summary_lenandsummary_snippedto control snippet length and count.