All Products
Search
Document Center

OpenSearch:RESTful API-based query demo

Last Updated:Feb 27, 2024

This topic provides sample code to show you how to use an SDK to call OpenSearch Retrieval Engine Edition to query data.

Sample code

import com.aliyun.ha3engine.Client;
import com.aliyun.ha3engine.models.*;
import com.aliyun.tea.TeaException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;


/**
 * @author alibaba
 */
public class SearchDoc {

    public static void main(String[] args) throws Exception {

        Config config = new Config();
        // The username. You can view the username on the API Endpoint tab of the Instance Details page.
        config.setAccessUserName("<userName>");
        // The password. You can change the password on the API Endpoint tab of the Instance Details page.
        config.setAccessPassWord("<password>");
        // The instance name. You can view the name in the upper-left corner of the Instance Details page. Example: ha-cn-i7*****605.
        config.setInstanceId("<instanceID>");

        // To access the instance by using an internal endpoint, uncomment the following line and specify the endpoint.
        //config.setEndpoint("ha-cn-******.ha.aliyuncs.com");
        // To access the instance by using a public endpoint, uncomment the following line and specify the endpoint.
        //config.setEndpoint("ha-cn-******.public.ha.aliyuncs.com");
        // To access the instance over the Internet, uncomment the following line and specify the HTTP proxy.
        // config.setHttpProxy("http://Public IP address:Port number");

        Client client = new Client(config);


        try {
            /*
            Example: Use RESTful API to query data.
             */
            // Specify the query parameters in the request body.
            JSONObject body = new JSONObject();
            body.put("query", "index_id:1");
            JSONObject configJson = new JSONObject();
            configJson.put("format", "json");
            body.put("config", configJson);
            // The name of the index table.
            String indexName = "index_odps";
            SearchRequestModel haQueryRequestModel = new SearchRequestModel();
            haQueryRequestModel.setBody(body.toJSONString());
            SearchResponseModel searchResponseModel = client.SearchRest(haQueryRequestModel, indexName);
            System.out.println("result:" + searchResponseModel.getBody());
        } catch (TeaException e) {
            System.out.println(e.getMessage());
            Map<String, Object> abc = e.getData();
            System.out.println(com.aliyun.teautil.Common.toJSONString(abc));
        }
    }
}