All Products
Search
Document Center

OpenSearch:Tutorial

Last Updated:Aug 10, 2023

Quick start

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

Configure environment variables

Configure the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables.

Important
  • The AccessKey pair of an Alibaba Cloud account can be used to access all API operations. We recommend that you use a Resource Access Management (RAM) user to call API operations or perform routine O&M. For information about how to use a RAM user, see Create a RAM user.

  • For information about how to create an AccessKey pair, see Create an AccessKey pair.

  • If you use the AccessKey pair of a RAM user, make sure that the required permissions are granted to the AliyunServiceRoleForOpenSearch role by using your Alibaba Cloud account. For more information, see AliyunServiceRoleForOpenSearch and Access authorization rules.

  • We recommend that you do not include your AccessKey pair in materials that are easily accessible to others, such as the project code. Otherwise, your AccessKey pair may be leaked and resources in your account become insecure.

  • Linux and macOS

    Run the following commands. Replace <access_key_id> and <access_key_secret> with the AccessKey ID and AccessKey secret of the RAM user that you use.

    export ALIBABA_CLOUD_ACCESS_KEY_ID=<access_key_id> 
    export ALIBABA_CLOUD_ACCESS_KEY_SECRET=<access_key_secret>
  • Windows

    1. Create an environment variable file, add the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables to the file, and then set the environment variables to your AccessKey ID and AccessKey secret.

    2. Restart Windows for the AccessKey pair to take effect.

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 and other related configurations based on your business requirements, such as 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 Configure Application page, click Import Template. In the Use Template panel, upload the application schema template, and complete the subsequent operations. You can use this application schema template to test the demo code for implementing the query and data push features. The demo code is provided by OpenSearch SDK for PHP that supports standard applications.

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 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. Then, you can 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;

// Import 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 your AccessKey pair.
// Obtain the configured AccessKey ID and AccessKey secret from the environment variables. 
// Configure environment variables before you run the sample code. For more information, see the "Configure the environment variables" section in this topic.
// Specify the AccessKey ID of your Alibaba Cloud account.
$accessKeyId = getenv('ALIBABA_CLOUD_ACCESS_KEY_ID');
// Specify the AccessKey secret of your Alibaba Cloud account.
$secret = getenv('ALIBABA_CLOUD_ACCESS_KEY_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

On the Instance Management page of 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 query feature.

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

Valid values of the cmd field are ADD, DELETE, and UPDATE. You can set the cmd field to ADD, DELETE, or UPDATE to add, delete, or update a document.

For standard applications, the cmd field supports only the ADD and DELETE operations. If you want 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.

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 sample code

Replace the configurations in the following sample code with your own information, and save the sample code as a PHP file. Download a V3 version of OpenSearch SDK for PHP and decompress the SDK package to the same directory in which the saved file resides. Then, you can use 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();
// Configure the start parameter in the config clause.
$params->setStart(0);
// Configure the hit 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 returned 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, more trials and iterations are required to gradually optimize search performance and improve the relevance of search results. In this process, you may encounter issues or search results that may not meet expectations. In these cases, you can run 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 the debugging information so that the technical engineers can analyze and identify the cause.

echo $ret->traceInfo->tracer;