全部产品

下拉提示Demo

V3.2.0 SDK 下拉列表搜索样例代码

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 = "填入accesskey信息";
    static private final String secret = "填入secret信息";
    static private final String host = "填入下拉提示关联应用所在区域的host";
    OpenSearch openSearch;
    OpenSearchClient openSearchClient;
    static private final byte hits = 8; //最大返回下拉提示的条数
    static private final String suggestionName = "填入下拉提示名称"; //填入下拉提示名称

    @Before
    public void setUp() {
        //初始化openSearch对象
        openSearch = new OpenSearch(accesskey, secret, host);
        openSearchClient = new OpenSearchClient(openSearch);
    }

    @Test
    public void TestEnv() {
        //查看文件和默认编码格式
        System.out.println(String.format("file.encoding: %s", System.getProperty("file.encoding")));
        System.out.println(String.format("defaultCharset: %s", Charset.defaultCharset().name()));

        //创建下拉提示对象
        SuggestionClient suggestionClient = new SuggestionClient(suggestionName, openSearchClient);
        String query = "填入查询词"; //填入查询词

        suggestionClient.setQuery(query); //设置查询词
        suggestionClient.setHits(hits); //设置最大返回下拉提示的条数

        try {
            String result = suggestionClient.search(); //查询
            System.out.println(result); //打印召回的结果
        } catch (OpenSearchException e) {
            e.printStackTrace();
        } catch (OpenSearchClientException e) {
            e.printStackTrace();
        }
    }
    @After
    public void clean() {
        openSearch.clear();
    }
}