All Products
Search
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.

<?php
// Import the header file.
require_once("../OpenSearch/Autoloader/Autoloader.php");
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.

<?php
header("Content-Type:text/html;charset=utf-8");
// Import the header file.
require_once("Config.inc.php");
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.
$params->setStart(0);
// Set the hits parameter in the config clause.
$params->setHits(20);
// Specify the application for which you want to implement the search feature.
$params->setAppName('The application name');
// Specify a query keyword.
$params->setQuery("name:'Search'");
// Specify the data format of return results. In this example, the data format is set to FULLJSON.
$params->setFormat("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.
print_r(json_decode($ret->result,true));
// Display debugging information.
echo $ret->traceInfo->tracer;