All Products
Search
Document Center

Tutorial

Last Updated: Sep 09, 2021

Quick start

This topic describes how to use OpenSearch SDK for PHP to implement the search feature with ease.

Before you begin

Create an application in the OpenSearch console

  • Log on to the OpenSearch console. Create an application and manually configure an application schema based on your business needs. Other configurations that you need to complete include index fields, attribute fields, data sources, and filter conditions.

  • OpenSearch provides an application schema template. You can download the template and use it to configure an application schema. On the application configuration page, click Import Template, upload the application schema template, and then complete the subsequent operations.You can use this application schema template to test the demo code for implementing the search and data push features by using OpenSearch SDK for PHP that supports standard applications.

Obtain your AccessKey ID and secret

Log on to the OpenSearch console, move the pointer over your profile picture in the upper-right corner, and then click AccessKey Management to check whether you have an AccessKey pair. If not, create one.

Download OpenSearch SDK for PHP and add it to your project

Download a V3 version of OpenSearch SDK for PHP and add the SDK to your project. You can find download links in the "Downloads" topic. Then, import the following header files to your project based on your business needs. For more information, see the demo code that OpenSearch provides for you to implement various features.

Header files for implementing the main features of OpenSearch

The main features of OpenSearch include application information query, application document query, document push, and drop-down suggestions. The following sample code shows how to import header files as dependencies and then use objects and methods to implement features.

<?php
// Import the header file for completing basic configurations, such as the AccessKey information, API endpoint, application name, drop-down suggestion name, and options.
require_once("../OpenSearch/Autoloader/Autoloader.php");
use OpenSearch\Client\OpenSearchClient;

// Import the header file for implementing the application information query feature.
require_once("Config.inc.php");
use OpenSearch\Client\AppClient;
use OpenSearch\Generated\Common\Pageable;

// Import the header file for implementing the document query feature.
require_once("Config.inc.php");
use OpenSearch\Client\SearchClient;
use OpenSearch\Util\SearchParamsBuilder;

// Introduce the header file for implementing the document push feature.
require_once("Config.inc.php");
use OpenSearch\Client\DocumentClient;

// Import the header file for implementing the drop-down suggestion feature.
require_once("Config.inc.php");
use OpenSearch\Client\SuggestClient;
use OpenSearch\Util\SuggestParamsBuilder;

Clients for implementing the main features of OpenSearch

To implement the main features of OpenSearch, you also need to create some clients.

<?php
// Import the header file for completing basic configurations.
require_once("Config.inc.php");

// Create a client for implementing the application information query feature.
$appClient = new AppClient($client);

// Create a client for implementing the document query feature.
require_once("Config.inc.php");
$searchClient = new SearchClient($client);

// Create a client for implementing the document push feature.
require_once("Config.inc.php");
$documentClient = new DocumentClient($client);

// Create a client for implementing the drop-down suggestion feature.
require_once("Config.inc.php");
$suggestClient = new SuggestClient($client);

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);

Data format of documents

After you complete the preceding configurations, use the DocumentClient object to upload documents to the newly-created application. The application name is specified by the $appName parameter in the header file for completing basic configurations. A document that can be uploaded to an OpenSearch application must be a JSON string. The following code shows the structure of a document.

Note

In the OpenSearch console, you can choose More > Upload File in the Actions column for an application. In the Upload File dialog box, you can download the sample file and upload it to the application to test the search feature.

[
    {
        "fields":{},
        "cmd":""
    }
...
]

Valid values of the cmd field are ADD, DELETE, and UPDATE.

For standard applications, the cmd field supports only the ADD and DELETE operations. If you need to update a document in a standard application, you must specify all the fields of the document instead of only the fields that you want to update. Therefore, updates of documents are also implemented by the ADD operation.

You can also set the cmd field to DELETE to delete data.

The fields field is used to define the core business data in a document. For example, if the application to which documents are to be uploaded is a novel search application, you can define fields such as title, body, and url.

Complete demo code

Replace the configurations in the following demo code with your own information, and then save the demo code to a PHP file. Download a V3 version of OpenSearch SDK for PHP and decompress the SDK package to the same directory where the saved file resides. Then, you can experiment with the main features of OpenSearch.

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

// Specify the table to which documents are to be uploaded.
$tableName = 'The table to which documents are to be uploaded';
// Create a DocumentClient object.
$documentClient = new DocumentClient($client);
// Add the document to be uploaded to an array.
$docs_to_upload = array();
for ($i = 0; $i < 10; $i++){
    $item = array();
    $item['cmd'] = 'ADD';
    $item["fields"] = array(
        "id" => $i + 1,
        "name" => "Search".$i
        );
    $docs_to_upload[] = $item;
}
// Encode the documents.
$json = json_encode($docs_to_upload);
// Call the push method to upload the documents.
$ret = $documentClient->push($json, $appName, $tableName);


// 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;

Debugging

The preceding configurations are sufficient to meet basic search requirements. However, to optimize search performance and improve the relevance of search results requires a long process of trial and error and iterations. In this process, you may encounter issues or search results may not meet expectations. In these cases, you can call the getRequestUrl method in the following sample code to obtain detailed information about the requests in question, and then use the information for troubleshooting. When you encounter an issue, you can seek help from the TradeManager or DingTalk support group of OpenSearch. You must provide debugging information so that the support engineers can analyze and identify the cause based on the information.

echo $ret->traceInfo->tracer;