All Products
Document Center

Demo code for implementing basic search features

Last Updated: Sep 09, 2021

Header file for completing basic configurations

The configurations that you specify in this header file will be used to implement the document push and document query features. The configurations include the AccessKey information, API endpoint, application name, drop-down suggestion name, and options.

// Import the header file.
use OpenSearch\Client\OpenSearchClient;

// Specify the AccessKey ID of your Alibaba Cloud account.
$accessKeyId = '<Your accessKeyId>';
// Specify the AccessKey secret of your Alibaba Cloud account.
$secret = '<Your secret>';
// Specify the endpoint of the OpenSearch API in your region. You can obtain the endpoint on the details page of the application in the OpenSearch console.
$endPoint = '<region endPoint>';
// Specify the application name.
$appName = '<app name>';
// Specify the drop-down suggestion name.
$suggestName = '<suggest name>';
// Enable the debugging mode.
$options = array('debug' => true);
// Create an OpenSearchClient object.
$client = new OpenSearchClient($accessKeyId, $secret, $endPoint, $options);

Implement the search feature

The following demo code shows how to implement a simple search feature.

// Import the header file.
use OpenSearch\Client\SearchClient;
use OpenSearch\Util\SearchParamsBuilder;
// Create a SearchClient object.
$searchClient = new SearchClient($client);
// Create a SearchParamsBuilder object.
$params = new SearchParamsBuilder();
// Set the start parameter in the config clause.
// Set the hits parameter in the config clause.
// Specify the application for which you want to implement the search feature.
$params->setAppName('The application name');
// Specify a query keyword.
// Specify the data format of return results. In this example, the data format is set to FULLJSON.
// Specify a field based on which documents are to be sorted.
$params->addSort('RANK', SearchParamsBuilder::SORT_DECREASE);
// Run the query and return the results.
$ret = $searchClient->execute($params->build());
// Decode the results that are in the JSON format.
// Display debugging information.
echo $ret->traceInfo->tracer;