Configuration des variables d'environnement
Configurez les variables d'environnement ALIBABA_CLOUD_ACCESS_KEY_ID et ALIBABA_CLOUD_ACCESS_KEY_SECRET.
La paire AccessKey d'un compte Alibaba Cloud permet d'accéder à toutes les opérations API. Nous vous recommandons d'utiliser un utilisateur RAM pour appeler les opérations API ou effectuer la maintenance courante. Pour savoir comment utiliser un utilisateur RAM, consultez la rubrique Créer un utilisateur RAM.
Pour savoir comment créer une paire AccessKey, consultez la rubrique Créer une paire AccessKey.
Si vous utilisez la paire AccessKey d'un utilisateur RAM, assurez-vous que le rôle AliyunServiceRoleForOpenSearch dispose des autorisations requises via votre compte Alibaba Cloud. Pour plus d'informations, consultez les rubriques AliyunServiceRoleForOpenSearch et Règles d'autorisation d'accès.
Nous vous déconseillons d'inclure votre paire AccessKey dans des supports facilement accessibles à des tiers, tels que le code du projet. Cela pourrait entraîner la divulgation de vos identifiants et compromettre la sécurité des ressources de votre compte.
-
Linux et macOS
Exécutez les commandes suivantes. Remplacez
<access_key_id>et<access_key_secret>par l'AccessKey ID et l'AccessKey Secret de l'utilisateur RAM utilisé.export ALIBABA_CLOUD_ACCESS_KEY_ID=<access_key_id> export ALIBABA_CLOUD_ACCESS_KEY_SECRET=<access_key_secret> -
Windows
Créez un fichier de variables d'environnement, ajoutez-y les variables ALIBABA_CLOUD_ACCESS_KEY_ID et ALIBABA_CLOUD_ACCESS_KEY_SECRET, puis définissez-les avec votre AccessKey ID et votre AccessKey Secret.
Redémarrez Windows pour que la paire AccessKey prenne effet.
Création d'un fichier d'en-tête contenant les configurations
Les configurations spécifiées dans ce fichier d'en-tête servent à envoyer et interroger des documents. Elles incluent la paire AccessKey, le point de terminaison API, le nom de l'application, le nom du modèle de suggestions déroulantes et les options.
$secret = getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET');<?php
// Import the header file.
require_once("../OpenSearch/Autoloader/Autoloader.php");
use OpenSearch\Client\OpenSearchClient;
// Specify your AccessKey pair.
// Obtain the AccessKey ID and AccessKey secret from environment variables.
// You must configure environment variables before you run this code. For more information, see the "Configure environment variables" section of this topic.
// Specify the AccessKey ID.
$accessKeyId = getenv('ALIBABA_CLOUD_ACCESS_KEY_ID');
// Specify the AccessKey secret.
$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 name of the drop-down suggestion model.
$suggestName = '<suggest name>';
// Enable the debugging mode.
$options = array('debug' => true);
// Create an OpenSearchClient object.
$client = new OpenSearchClient($accessKeyId, $secret, $endPoint, $options);
Envoi de documents
Le code suivant télécharge 10 documents vers une application 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 you want to push documents.
$tableName = 'The table to which you want to push documents';
// Create a DocumentClient object.
$documentClient = new DocumentClient($client);
// Add the documents to be pushed 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 for KFC".$i
);
$docs_to_upload[] = $item;
}
// Encode the documents.
$json = json_encode($docs_to_upload);
// Call the push method to push the documents.
$ret = $documentClient->push($json, $appName, $tableName);
// Hibernate the thread for 10 seconds. If you push documents to the primary table of an advanced application, 90% of the documents can be synchronized within 10 seconds and 99% of the documents are available within 10 minutes. However, this is not applicable to document push to secondary tables.
sleep(10);
// Create a SearchClient object.
$searchClient = new SearchClient($client);
// Create a SearchParamsBuilder object.
$params = new SearchParamsBuilder();
// Specify the start parameter in the config clause.
$params->setStart(0);
// Specify the hits parameter in the config clause.
$params->setHits(20);
// Specify the application for which you want to implement search features.
$params->setAppName('The application name');
// Specify a search query.
$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 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;