Tutorials
Getting started
OpenSearch makes it easy to provide search features. This guide helps you get started quickly.
Configure environment variables
Configure the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables.
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
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.
Restart Windows for the AccessKey pair to take effect.
Preparations
Log on to the console and create an application
In the console, you can manually create a table schema and configure other settings as needed, such as indexes, properties, data sources, and filter conditions.
Download the provided test Standard Edition application schema template. When you create the application schema, select Create application schema from template and click Next. In the upper-left corner, select Import template and upload the template you downloaded. Click Next until the process is complete. This test template for application schemas is compatible with the search and data push demo code in the Standard Edition PHP SDK documentation.
Download the PHP SDK and add it to your project
In the navigation pane on the left, go to the Related downloads page and download the v3 PHP SDK package. Add the required header files to your project based on the features you need. For more information, see the code samples for each feature in the demo.
Main feature header files (for reference)
The main features include querying application information, querying documents, pushing documents, and providing drop-down suggestions. After you reference the header files for these features, you can write the corresponding functions and call the object methods.
<?php
// Config page, header file. Contains the AccessKey, host, application name, suggestion name, options, and other information.
require_once("../OpenSearch/Autoloader/Autoloader.php");
use OpenSearch\Client\OpenSearchClient;
// Header file for getting the application list.
require_once("Config.inc.php");
use OpenSearch\Client\AppClient;
use OpenSearch\Generated\Common\Pageable;
// Header file for querying documents.
require_once("Config.inc.php");
use OpenSearch\Client\SearchClient;
use OpenSearch\Util\SearchParamsBuilder;
// Header file for pushing documents.
require_once("Config.inc.php");
use OpenSearch\Client\DocumentClient;
// Header file for drop-down suggestions.
require_once("Config.inc.php");
use OpenSearch\Client\SuggestClient;
use OpenSearch\Util\SuggestParamsBuilder;Main feature client collection (for reference)
First, instantiate an SDK client. You will use this client when you write the functions for specific features.
<?php
// Reference the configuration header file.
require_once("Config.inc.php");
// Create a client to get the application list.
$appClient = new AppClient($client);
// Create a client to query documents.
require_once("Config.inc.php");
$searchClient = new SearchClient($client);
// Create a client to push documents.
require_once("Config.inc.php");
$documentClient = new DocumentClient($client);
// Create a client for drop-down suggestion queries.
require_once("Config.inc.php");
$suggestClient = new SuggestClient($client);Create a Config header file
The content of the Config file serves as the header file for subsequent document query and push operations. It contains important parameters such as the AccessKey, host, application name, suggestion name, and options.
<?php
// Import the header file.
require_once("../OpenSearch/Autoloader/Autoloader.php");
use OpenSearch\Client\OpenSearchClient;
// User identification information.
// Read the configured AccessKey ID and AccessKey Secret from environment variables.
// Before you run the code sample, you must configure environment variables. See the "Configure environment variables" step above.
// Replace with your AccessKey ID.
$accessKeyId = getenv('ALIBABA_CLOUD_ACCESS_KEY_ID');
// Replace with your AccessKey secret.
$secret = getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET');
// Replace with the endpoint for your region. You can find the endpoint on the Basic Information page of your application in the console.
$endPoint = '<region_endpoint>';
// Replace with your application name.
$appName = '<app_name>';
// Replace with your suggestion name.
$suggestName = '<suggest_name>';
// Enable the debug mode.
$options = array('debug' => true);
// Create an OpenSearchClient object.
$client = new OpenSearchClient($accessKeyId, $secret, $endPoint, $options);Upload document format
Building on the previous code, you can use the DocumentClient class object to upload documents to your application. Continue to use the `$appName` variable from the config file. A document in an OpenSearch application is a JSON-formatted string with the following structure:
In the application console, click the Upload File button and refer to the sample data to download the complete document data format. You can then upload this file to your application and search its contents.
[
{
"fields":{},
"cmd":""
}
...
]The valid values for the cmd field are ADD, DELETE, and UPDATE.
Standard Edition applications do not support `UPDATE` operations. All additions and updates are performed using the `ADD` operation, which prevents partial field updates.
), used to add, delete, and update a document, respectively.
The fields object contains the fields of the document. For example, a novel application may contain the following fields: title for the name of the novel, body for the main content of the novel, and url for the URL to access the novel.
Complete code sample
Download the v3 PHP SDK and extract it to the same directory as the following code file. Then, you can copy the code, replace the AccessKey, secret, and other key information with your own, and run it to test OpenSearch.
<?php
header("Content-Type:text/html;charset=utf-8");
// Reference the header file.
require_once("Config.inc.php");
use OpenSearch\Client\DocumentClient;
use OpenSearch\Client\SearchClient;
use OpenSearch\Util\SearchParamsBuilder;
// Set the name of the table to which data will be pushed.
$tableName = 'replace_with_your_table_name';
// Create a document operation client.
$documentClient = new DocumentClient($client);
// Add document data.
$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.
$json = json_encode($docs_to_upload);
// Submit and push the document.
$ret = $documentClient->push($json, $appName, $tableName);
// Instantiate a search class.
$searchClient = new SearchClient($client);
// Instantiate a search parameter class.
$params = new SearchParamsBuilder();
// Set the start value of the config clause.
$params->setStart(0);
// Set the hits value of the config clause.
$params->setHits(20);
// Specify an application for the search.
$params->setAppName('replace_with_your_app_name');
// Specify the search keyword.
$params->setQuery("name:'search'");
// Specify the format of the search results as JSON.
$params->setFormat("fulljson");
// Add a sort field.
$params->addSort('RANK', SearchParamsBuilder::SORT_DECREASE);
// Execute the search and get the results.
$ret = $searchClient->execute($params->build());
// Decode the JSON string.
print_r(json_decode($ret->result,true));
// Print the debug information.
echo $ret->traceInfo->tracer;Debug
You can now use the basic search feature. Optimizing search and improving result relevance is a long process that requires continuous testing and iteration. If you encounter problems or receive unexpected results, you can use the following interface to obtain detailed request information for troubleshooting. When you ask for help in DingTalk groups, this debug information helps us quickly identify the cause of the problem.
echo $ret->traceInfo->tracer;