All Products
Document Center

OpenSearch:Demo code for pushing data

Last Updated:Sep 09, 2021

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.

// Import the header file.
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);

Upload documents

In the following code, 10 documents are uploaded to an OpenSearch application.

// Import the header file.
use OpenSearch\Client\DocumentClient;
// Specify the table to which data is to be uploaded.
$tableName = 'The table to which data is to be uploaded';
// Create a DocumentClient object.
$documentClient = new DocumentClient($client);
// Add the documents 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 data to be uploaded into a JSON string.
$json = json_encode($docs_to_upload);
// Call the push method to upload the documents.
$ret = $documentClient->push($json, $appName, $tableName);