All Products
Search
Document Center

Demo code for implementing drop-down suggestions

Last Updated: Sep 09, 2021

Demo code for implementing drop-down suggestions by using OpenSearch SDK for Java V3.2.0

package com.example.opensearch;

import com.aliyun.opensearch.OpenSearchClient;
import com.aliyun.opensearch.SuggestionClient;
import com.aliyun.opensearch.sdk.generated.OpenSearch;
import com.aliyun.opensearch.sdk.generated.commons.OpenSearchClientException;
import com.aliyun.opensearch.sdk.generated.commons.OpenSearchException;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.nio.charset.Charset;

public class SuggestDemo {
    static private final String accesskey = "The AccessKey ID of your Alibaba Cloud account";
    static private final String secret = "The AccessKey secret of your Alibaba Cloud account";
    static private final String host = "The endpoint of the OpenSearch API in the region of the application for which you want to implement drop-down suggestions";
    OpenSearch openSearch;
    OpenSearchClient openSearchClient;
    static private final byte hits = 8; // Specify the maximum number of drop-down suggestions that can be returned.
    static private final String suggestionName = "The name of the drop-down suggestion"; // Specify the name of the drop-down suggestion.

    @Before
    public void setUp() {
        // Create an OpenSearch object.
        openSearch = new OpenSearch(accesskey, secret, host);
        openSearchClient = new OpenSearchClient(openSearch);
    }

    @Test
    public void TestEnv() {
        // View documents and the default encoding format.
        System.out.println(String.format("file.encoding: %s", System.getProperty("file.encoding")));
        System.out.println(String.format("defaultCharset: %s", Charset.defaultCharset().name()));

        // Create a SuggestionClient object.
        SuggestionClient suggestionClient = new SuggestionClient(suggestionName, openSearchClient);
        String query = "The query keyword";
try {
            SuggestParams suggestParams = new SuggestParams();
            suggestParams.setQuery(query); // Specify a query keyword.
            suggestParams.setHits(hits); // Specify the maximum number of drop-down suggestions that can be returned.
            suggestParams.setUserId("12345678"); // Specify a user ID.
            SearchResult result = suggestionClient.execute(suggestParams); 
            System.out.println(result); // Display the retrieval results.
        } catch (OpenSearchException e) {
            e.printStackTrace();
        } catch (OpenSearchClientException e) {
            e.printStackTrace();
        }
    }

    @After
    public void clean() {
        openSearch.clear();
    }
}