Demo code for implementing basic search features

更新时间:
复制 MD 格式

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:

Important

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

  1. Create an environment variable file and add ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET with their corresponding values.

  2. 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:

PlaceholderDescription
<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-parameterValueDescription
start0Offset of the first hit to return
hit50Maximum number of hits to return
formatfulljsonResponse format
querydefault:'<words>'Searches the default field for the specified term

Summary highlighting

The summary parameter highlights matched keywords in the response. The example configures:

Sub-parameterValueDescription
summary_fielddescriptionField to generate the highlighted snippet from
summary_len50Maximum character length of the snippet
summary_ellipsis...String appended when the snippet is truncated
summary_snipped1Number 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

ParameterValueDescription
ConnectTimeout5000Connection timeout in milliseconds
ReadTimeout10000Read timeout in milliseconds
AutoretryfalseWhether to retry failed requests automatically
IgnoreSSLfalseWhether to skip SSL certificate verification
MaxIdleConns50Maximum number of idle connections in the connection pool

Next steps

  • Customize the query parameter 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_len and summary_snipped to control snippet length and count.