All Products
Search
Document Center

OpenSearch:Tutorials

Last Updated:Apr 01, 2026

This tutorial walks you through integrating OpenSearch into a PHP application using OpenSearch SDK for PHP. By the end, you will have pushed documents to an OpenSearch application and run your first search query.

Note

This tutorial covers a minimal working integration using the PHP SDK. For production deployments, see the SDK reference documentation and the application schema configuration guide.

Prerequisites

Before you begin, make sure you have:

  • An Alibaba Cloud account with an OpenSearch application created and configured (index fields, attribute fields, data sources, and filter conditions)

  • OpenSearch SDK for PHP (V3) downloaded from the Downloads topic and added to your project

  • A Resource Access Management (RAM) user with the required permissions granted to the AliyunServiceRoleForOpenSearch role. See AliyunServiceRoleForOpenSearch and Access authorization rules

Note

To set up your application schema quickly, download the application schema template. In the OpenSearch console, go to the Configure Application page, click Import Template, and upload the file. This template is compatible with the demo code in this tutorial.

Step 1: Configure credentials

Store your AccessKey credentials as environment variables. Never hardcode credentials in source files.

Important

Use a RAM user rather than your Alibaba Cloud account's root credentials. See Create a RAM user and Create an AccessKey pair.

Linux and macOS

Replace <access_key_id> and <access_key_secret> with your RAM user's AccessKey ID and AccessKey secret.

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 and add ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET with their respective values.

  2. Restart Windows for the changes to take effect.

Step 2: Set up the base configuration

Create a Config.inc.php file that all other parts of your integration will share. It initializes the OpenSearch client with your credentials, endpoint, and application name.

<?php
// Import the autoloader.
require_once("../OpenSearch/Autoloader/Autoloader.php");
use OpenSearch\Client\OpenSearchClient;

// Read credentials from environment variables.
$accessKeyId = getenv('ALIBABA_CLOUD_ACCESS_KEY_ID');
$secret      = getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET');

// Set the API endpoint for your region.
// Find this value on the application details page in the OpenSearch console.
$endPoint    = '<region endPoint>';

// Set the application name and drop-down suggestion name.
$appName     = '<app name>';
$suggestName = '<suggest name>';

// Enable debug mode to capture trace information.
$options = array('debug' => true);

// Create the OpenSearch client.
$client = new OpenSearchClient($accessKeyId, $secret, $endPoint, $options);

Replace <region endPoint>, <app name>, and <suggest name> with values from the OpenSearch console.

Step 3: Import header files and create clients

OpenSearch SDK for PHP uses feature-specific clients. Import the header files for the features you need, then instantiate the corresponding client objects.

Header files

<?php
// Base configuration (required for all features).
require_once("../OpenSearch/Autoloader/Autoloader.php");
use OpenSearch\Client\OpenSearchClient;

// Application information query.
require_once("Config.inc.php");
use OpenSearch\Client\AppClient;
use OpenSearch\Generated\Common\Pageable;

// Document query (search).
require_once("Config.inc.php");
use OpenSearch\Client\SearchClient;
use OpenSearch\Util\SearchParamsBuilder;

// Document push.
require_once("Config.inc.php");
use OpenSearch\Client\DocumentClient;

// Drop-down suggestions.
require_once("Config.inc.php");
use OpenSearch\Client\SuggestClient;
use OpenSearch\Util\SuggestParamsBuilder;

Client objects

<?php
require_once("Config.inc.php");

// Application information query client.
$appClient = new AppClient($client);

// Document query (search) client.
$searchClient = new SearchClient($client);

// Document push client.
$documentClient = new DocumentClient($client);

// Drop-down suggestion client.
$suggestClient = new SuggestClient($client);

The following table summarizes the four clients and their roles:

ClientClassPurpose
$appClientAppClientQuery application information
$searchClientSearchClientExecute search queries
$documentClientDocumentClientPush documents
$suggestClientSuggestClientRetrieve drop-down suggestions

Step 4: Push documents

Documents pushed to OpenSearch must be JSON strings. Each document is an object with two fields:

FieldDescription
cmdOperation to perform. Valid values: ADD, DELETE, UPDATE. For standard applications, only ADD and DELETE are supported — to update a document, use ADD and supply all fields.
fieldsKey-value pairs that define the document content (for example, title, body, url).
Note

To test with sample data, go to the Instance Management page in the OpenSearch console, click More > Upload File in the Actions column, and download the sample file from the Upload File dialog box.

The following example pushes 10 documents using the ADD operation:

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

// Specify the table to push documents to.
$tableName = '<table name>';

$documentClient = new DocumentClient($client);

// Build the document 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 and push.
$json = json_encode($docs_to_upload);
$ret  = $documentClient->push($json, $appName, $tableName);

A successful push returns an HTTP 200 response. If $ret->traceInfo->tracer contains error details, see Step 6: Debug requests.

Step 5: Run a search query

Use SearchClient and SearchParamsBuilder to build and execute a query.

<?php
require_once("Config.inc.php");
use OpenSearch\Client\SearchClient;
use OpenSearch\Util\SearchParamsBuilder;

$searchClient = new SearchClient($client);
$params       = new SearchParamsBuilder();

// config clause parameters.
$params->setStart(0);     // Starting offset of results.
$params->setHits(20);     // Number of results to return.

// Query parameters.
$params->setAppName('<app name>');
$params->setQuery("name: 'Search'");
$params->setFormat('fulljson');

// Sort by relevance score in descending order.
$params->addSort('RANK', SearchParamsBuilder::SORT_DECREASE);

// Execute and decode.
$ret    = $searchClient->execute($params->build());
$result = json_decode($ret->result, true);
print_r($result);

If the result is empty or unexpected, check your query keyword and index field configuration.

Step 6: Debug requests

When a query returns unexpected results or an operation fails, print the trace information to get full request and response details:

echo $ret->traceInfo->tracer;

When escalating an issue to OpenSearch technical support via TradeManager or the DingTalk support group, include the full tracer output.

What's next

  • Explore the full API: See the SDK reference documentation for all available query parameters, including filter conditions, aggregate queries, and custom ranking.

  • Enable drop-down suggestions: Use SuggestClient and SuggestParamsBuilder with the $suggestName configured in Config.inc.php.