All Products
Search
Document Center

OpenSearch:Demo code for querying drop-down suggestions

Last Updated:Feb 06, 2023

Create a header file that contains 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 pair, API endpoint, application name, name of the drop-down suggestion model, 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 name of the drop-down suggestion model.
$suggestName = '<suggest name>';
// Enable the debugging mode.
$options = array('debug' => true);
// Create an OpenSearchClient object.
$client = new OpenSearchClient($accessKeyId, $secret, $endPoint, $options);

Example

The following sample code shows how to implement drop-down suggestions. For more information about the complete code, see the "Complete sample code" section in the "Tutorial" topic.

<?php
header("Content-Type:text/html;charset=utf-8");
// Import the header file.
require_once("Config.inc.php");
use OpenSearch\Client\SuggestClient;
use OpenSearch\Util\SuggestParamsBuilder;

// Create a SuggestClient object.
$suggestClient = new SuggestClient($client);
// Create a SuggestParamsBuilder object for the drop-down suggestion to be created.
$params = SuggestParamsBuilder::build($appName, $suggestName, '<Query keyword of the drop-down suggestion to be created>', 10);

// Run the query and return drop-down suggestions.
$ret = $suggestClient->execute($params);
// Display the return results.
print_r(json_decode($ret->result, true));

// Display debugging information.
echo $ret->traceInfo->tracer;