Demo for all search features

更新时间:
复制 MD 格式

This page shows how to run a full-featured document search using the OpenSearch PHP SDK. The demo covers pagination, sorting, filtering, deduplication, aggregation, and snippet summaries in a single query.

Prerequisites

Before you begin, make sure you have:

  • An OpenSearch application. Find the endpoint and application name on the Basic Information page of the application in the console.

  • An AccessKey pair for a Resource Access Management (RAM) user with the required permissions. See AliyunServiceRoleForOpenSearch for role setup details, and review Access authorization rules to confirm the required permissions.

  • The OpenSearch PHP SDK installed.

Important

Use a RAM user's AccessKey pair instead of your Alibaba Cloud account's AccessKey pair. Account-level credentials grant access to all API operations and pose a security risk if exposed. Never hardcode credentials in your source code.

Set environment variables

Store your credentials as environment variables to keep them out of your source code.

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 your AccessKey ID and AccessKey secret as values.

  2. Restart Windows for the variables to take effect.

Create a configuration file

Create Config.inc.php as a shared header for all search and document push operations. 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');

// Your application's endpoint — find it on the Basic Information page in the console.
$endPoint = '<region endPoint>';

// Your OpenSearch application name.
$appName = '<app name>';

// Enable debug mode to print request and response details.
$options = array('debug' => true);

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

Run a full search query

The following example submits a search query with all major parameters configured. Import Config.inc.php first, then build and execute the query with SearchParamsBuilder.

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

// Import the shared configuration.
require_once("Config.inc.php");
use OpenSearch\Client\SearchClient;
use OpenSearch\Util\SearchParamsBuilder;

$searchClient = new SearchClient($client);

// Build the query parameters.
$params = new SearchParamsBuilder();

// Pagination: start at offset 0, return up to 20 results.
$params->setStart(0);
$params->setHits(20);

// Target application and query.
$params->setAppName('Replace with your application name');
$params->setQuery("name:'search'");

// Return results as full JSON.
$params->setFormat("fulljson");

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

// Filter: only return documents where id > 0.
$params->setFilter('id>0');

// Distinct clause: deduplicate by cate_id, keeping one result per category.
$params->addDistinct(
    array('key' => 'cate_id', 'distTimes' => 1, 'distCount' => 1, 'reserved' => 'false')
);

// Summary: highlight matched terms in the name field, up to 100 characters per snippet.
$params->addSummary(
    array('summary_field' => 'name', 'summary_len' => 100, 'summary_ellipsis' => "...", 'summary_snippet' => 2, 'summary_element_prefix' => '', 'summary_element_postfix' => '')
);

// Link this request to a previous search session for query analysis.
$params->setCustomParam('from_request_id', '159851481919726888064081');

// Aggregate clause: count documents grouped by cate_id, sampling up to 10 groups.
$params->addAggregate(
    array('groupKey' => 'cate_id', 'aggFun' => 'count()', 'range' => '1', 'aggSamplerThresHold' => 1, 'aggSamplerStep' => 10, 'maxGroup' => 10)
);
// Example with aggFilter to restrict aggregation to a subset of documents:
// $params->addAggregate(
//     array('groupKey' => 'cate_id', 'aggFun' => 'count()', 'range' => '1', 'aggFilter' => 'id>1', 'aggSamplerThresHold' => 1, 'aggSamplerStep' => 10, 'maxGroup' => 10)
// );

// First rank (rough sort): use the default rough-sort expression.
$params->setFirstRankName('default');

// Second rank (fine sort): use the default fine-sort expression.
$params->setSecondRankName('default');

// Specify which fields to return in the response.
$params->setFetchFields(array('id', 'name', 'phone', 'int_arr', 'literal_arr', 'float_arr', 'cate_id'));

// Set the raw query string for query analysis.
$params->setRawQuery("string");

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

// Print the content of the returned information.
print_r(json_decode($ret->result,true));

// Print debug trace for troubleshooting.
echo $ret->traceInfo->tracer;

What's next