All Products
Search
Document Center

Demo code for implementing the search feature

Last Updated: Sep 09, 2021

Demo code for implementing the search feature by using OpenSearch SDK for Java V3.1

Note: Determine whether an error has occurred based on the error code and message instead of the status information.

For more information about errors, see Error codes.

Demo code provided by OpenSearch SDK for Java

package com.aliyun.opensearch;
import com.aliyun.opensearch.sdk.dependencies.com.google.common.collect.Lists;
import com.aliyun.opensearch.sdk.dependencies.org.json.JSONObject;
import com.aliyun.opensearch.sdk.generated.OpenSearch;
import com.aliyun.opensearch.sdk.generated.commons.OpenSearchClientException;
import com.aliyun.opensearch.sdk.generated.commons.OpenSearchException;
import com.aliyun.opensearch.sdk.generated.search.*;
import com.aliyun.opensearch.sdk.generated.search.general.SearchResult;
import com.aliyun.opensearch.search.SearchParamsBuilder;
import com.aliyun.opensearch.search.SearchResultDebug;
import java.nio.charset.Charset;
public class testSearch {
    private static String appName = "The name of the OpenSearch application for which you want to implement the search feature";
    private static String accesskey = "The AccessKey ID of your Alibaba Cloud account";
    private static String secret = "The AccessKey secret of your Alibaba Cloud account";
    private static String host = "The endpoint of the OpenSearch API in your region";
    public static void main(String[] args) {
            // 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 an OpenSearch object.
            OpenSearch openSearch = new OpenSearch(accesskey, secret, host);
            // Use the OpenSearch object as a parameter to create an OpenSearchClient object.
            OpenSearchClient serviceClient = new OpenSearchClient(openSearch);
            // Use the OpenSearchClient object as a parameter to create a SearcherClient object.
            SearcherClient searcherClient = new SearcherClient(serviceClient);
            // Create a Config object and use the config clause to configure parameters such as the application name, paging-related parameters, and data format of return results.
            Config config = new Config(Lists.newArrayList(appName));
            config.setStart(0);
            config.setHits(5);
            // Specify the data format of return results. Supported formats include XML, JSON, and FULLJSON. In this example, the data format is set to FULLJSON.
            config.setSearchFormat(SearchFormat.FULLJSON);
            // Specify the fields to be returned in search results.
            config.setFetchFields(Lists.newArrayList("id", "name", "phone", "int_arr", "literal_arr", "float_arr", "cate_id"));
            // Note: The rerank_size parameter in the Config class is set by the setReRankSize method of the Rank class.
            // Specify the kvpairs clause. In this example, the uniq plug-in is added to the distinct clause. This ensures that the values of the total and viewtotal parameters are accurate if the reserved parameter is set to false.
            //config.setKvpairs("duniqfield:cate_id");
            // Create a SearchParams object.
            SearchParams searchParams = new SearchParams(config);
            // Specify the query clause. You can specify multiple keywords to perform a query based on multiple index fields. In this case, you must specify the index fields in one setQuery call. If you specify each index field in a separate setQuery call, the last clause overwrites the preceding clauses.
            searchParams.setQuery("name:'opensearch'");
            // Create a Distinct object.
            Distinct dist = new Distinct();
            dist.setKey("cate_id"); // Specify a field to be used for distinct extraction.
            dist.setDistCount(1); // Specify the number of documents that are extracted each time.
            dist.setDistTimes(1); // Specify the number of times of extraction.
            dist.setReserved(false); // Specify whether to retain the remaining documents after extraction.
            dist.setUpdateTotalHit(false); // Specify whether to subtract the number of discarded documents from the value of the totalHits parameter if the reserved parameter is set to false.
            dist.setDistFilter("cate_id<=3"); // Specify a filter condition to be used to select documents to be extracted.
            dist.setGrade("1.2"); // Specify a threshold for distinct extraction.
            // The duniqfield parameter is specified in the form of a kvpairs clause in the config clause.
            // Add the Distinct object as a query parameter.
            searchParams.addToDistincts(dist);
            // Create an Aggregate object.
            Aggregate agg = new Aggregate();
            agg.setGroupKey("cate_id"); // Specify a field to be aggregated.
            agg.setAggFun("count()"); // Specify an aggregation function.
            agg.setAggFilter("cate_id=1"); // Specify an aggregation filter.
            agg.setRange("0~10"); // Specify an aggregation range.
            agg.setAggSamplerThresHold("5"); // Set a threshold for sampled aggregation.
            agg.setAggSamplerStep("5"); // Specify a threshold for sampled aggregation.
            agg.setMaxGroup("5"); // Specify the maximum number of groups that can be returned.
            // Add the Aggregate object as a query parameter.
            //searchParams.addToAggregates(agg);
            // Specify a filter condition.
            // searchParams.setFilter("id > \"0\""); // You can also set a filter condition by using the SearchParamsBuilder class.
            // Specify a sorting condition.
            Sort sorter = new Sort();
            sorter.addToSortFields(new SortField("id", Order.DECREASE)); // Specify a field based on which documents are to be sorted, and a sorting method. In this example, documents are sorted based on the id field in descending order.
            sorter.addToSortFields(new SortField("RANK", Order.INCREASE)); // If multiple documents have the same value of the id field, sort the documents based on the RANK field in ascending order.
            // Add the Sort object as a query parameter.
            searchParams.setSort(sorter);
            // Specify a rough sort expression and a fine sort expression. In this example, the default expressions are used.
            Rank rank = new Rank();
            rank.setFirstRankName("default");
            rank.setSecondRankName("default");
            rank.setReRankSize(5);// Specify the number of documents to be sorted based on the fine sort expression.
            // Add the Aggregate object as a query parameter.
            searchParams.setRank(rank);
        // Set the re_search parameter.
        //strategy:threshold,params:total_hits#10 => "strategy:threshold" indicates the query strategy. Only one strategy is supported. 
        // Use the total_hits parameter to set a threshold. If the value of the total_hits parameter for the first run of a query is less than the specified threshold, the query is run again. 
        Map<String, String> reSearchParams = new HashMap<String, String>();
        reSearchParams.put("re_search", "strategy:threshold,params:total_hits#10");
        // Specify the from_request_id parameter for queries that are associated with drop-down suggestions.
        reSearchParams.put("from_request_id", "159851481919726888064081");
 
        //searchParams.setCustomParam(reSearchParams);
        // Create a Summary object. In this example, the search result summary is added as a query parameter by using a SearchParamsBuilder object.
        Summary summ = new Summary("name");
        summ.setSummary_field("name");// Specify a field based on which a summary is to be generated. This field must be of the text type so that the field can be analyzed. 
        summ.setSummary_len("50");// Specify the length of each snippet.
        summ.setSummary_element("em"); // Specify a label to be used for highlighting.
        summ.setSummary_ellipsis("..."); // Specify a string to be used to represent the data that is not displayed.
        summ.setSummary_snippet("1");// Specify the number of summary snippets that each query can hit.
        // Add the Summary object as a query parameter.
        // searchParams.addToSummaries(summ);
            // Create a SearchParamsBuilder object. As the utility class of SearchParams, the SearchParamsBuilder class allows you to configure query-related parameters with ease.
            SearchParamsBuilder paramsBuilder = SearchParamsBuilder.create(searchParams);
            // Use the SearchParamsBuilder object to add the previously created search result summary as a query parameter.
            paramsBuilder.addSummary("name", 50, "em", "...", 1);
            // Specify a filter condition.
            paramsBuilder.addFilter("id>=0", "AND");
            try {
                // Run the query and return the results. Determine whether an error has occurred based on the error code and message. For more information about errors, see the "Error codes" topic. 
                SearchResult searchResult = searcherClient.execute(paramsBuilder);
                String result = searchResult.getResult();
                JSONObject obj = new JSONObject(result);
                // Display the search results.
                System.out.println(obj.toString());
                // You may need the information about request addresses for debugging.
                SearchResultDebug searchdebugrst = searcherClient.executeDebug(searchParams);
                // Display the request string of the last query.
                System.out.println(searchdebugrst.getRequestUrl());
            } catch (OpenSearchException e) {
                e.printStackTrace();
            } catch (OpenSearchClientException e) {
                e.printStackTrace();
            }
        }
}