Demo code for implementing basic search features

更新时间:
复制 MD 格式

This page shows how to run a basic search query against an OpenSearch application using the PHP SDK — from setting credentials to reading the response.

Prerequisites

Before you begin, ensure that you have:

Important

Use a RAM user's AccessKey pair rather than your Alibaba Cloud account's AccessKey pair. An account-level AccessKey pair has access to all API operations, and embedding it in code risks exposing it.

Set environment variables

Store your credentials as environment variables rather than hardcoding them in your project.

  • Linux and macOS — run the following commands, replacing the placeholders 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 — create an environment variable file, add ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET with the corresponding values, then restart Windows for the changes to take effect.

Create the configuration file

Create Config.inc.php to hold the shared settings used by both the push and query code, including the AccessKey pair, API endpoint, application name, name of the drop-down suggestion model, and options. All other PHP files import this file.

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

// Read credentials from environment variables set in the previous step.
// Do not hardcode credentials in source files.
$accessKeyId = getenv('ALIBABA_CLOUD_ACCESS_KEY_ID');
$secret      = getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET');

// The API endpoint for your region — copy it from the application details page
// in the OpenSearch console.
$endPoint = '<region endPoint>';

// The name of the OpenSearch application you want to query.
$appName = '<app name>';

// Enable debug mode to print trace information alongside search results.
// Set to false (or remove the option) in production.
$options = array('debug' => true);

// Initialize the client. All subsequent API calls use this $client instance.
$client = new OpenSearchClient($accessKeyId, $secret, $endPoint, $options);

Run a search query

The following example runs a basic search query and prints the decoded JSON response.

<?php
header("Content-Type:text/html;charset=utf-8");

// Import shared configuration (credentials, endpoint, app name, client).
require_once("Config.inc.php");
use OpenSearch\Client\SearchClient;
use OpenSearch\Util\SearchParamsBuilder;

// Wraps $client with search-specific methods.
$searchClient = new SearchClient($client);

// Build the query parameters.
$params = new SearchParamsBuilder();
$params->setStart(0);    // Offset of the first result. Increment by setHits() value for pagination (20, 40, 60, ...).
$params->setHits(20);    // Number of results to return per page.
$params->setAppName('The application name');
$params->setQuery("name: 'Search'");                              // Field-specific query: field name followed by the search term.
$params->setFormat("fulljson");                                   // Specify the data format of returned results.
$params->addSort('RANK', SearchParamsBuilder::SORT_DECREASE);     // Sort by the specified field.

// Execute the query.
$ret = $searchClient->execute($params->build());

// Decode and print the JSON response.
print_r(json_decode($ret->result, true));

// Print debug trace (request timing, query rewriting details).
// Only available when debug mode is enabled in Config.inc.php.
echo $ret->traceInfo->tracer;