Demo code for implementing comprehensive search features

更新时间:
复制 MD 格式

This page provides PHP demo code that performs a search request against an OpenSearch Industry Algorithm Edition application, covering querying, filtering, sorting, aggregation, snippet highlighting, and distinct deduplication.

Prerequisites

Before you begin, make sure you have:

Important

Use a RAM user's AccessKey pair, not an Alibaba Cloud account's AccessKey pair. An Alibaba Cloud account has unrestricted access to all API operations. Never embed AccessKey pairs directly in project code. See Create a RAM user.

Step 1: Set environment variables

Set the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables to your RAM user's AccessKey ID and AccessKey secret.

  • Linux and macOS — run the following commands, replacing the placeholders with your actual values:

    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 both variables, set them to your AccessKey ID and AccessKey secret, then restart Windows for the changes to take effect.

Step 2: Create the configuration file

Create a file named Config.inc.php. This file initializes the OpenSearch client and is imported by the search script in the next step.

<?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');

// Specify the API endpoint for your region.
// Find the endpoint on the application details page 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 debug mode to print trace information.
$options = array('debug' => true);

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

Replace the following placeholders:

PlaceholderDescription
<region endPoint>The API endpoint for your region, found on the application details page in the OpenSearch console
<app name>The name of your OpenSearch application
<suggest name>The name of your drop-down suggestion model

Step 3: Run the search

The following script imports Config.inc.php and runs a search request. Each feature is configured through a dedicated method on SearchParamsBuilder.

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

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

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

// --- Pagination ---
$params->setStart(0);   // Starting offset of results
$params->setHits(20);   // Number of results per page

// --- Application and query ---
$params->setAppName('Application name');
$params->setQuery("name:'Search'");
$params->setFormat("fulljson");  // Return results as full JSON

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

// --- Filtering ---
$params->setFilter('id>0');

// --- Distinct deduplication ---
// Return at most 1 result per unique cate_id value.
$params->addDistinct(
    array('key' => 'cate_id', 'distTimes' => 1, 'distCount' => 1, 'reserved' => 'false')
);

// --- Summary (snippet highlighting) ---
// Highlight matched terms in the 'name' field, cropped to 100 characters,
// with up to 2 snippet fragments separated by ". . ."
$params->addSummary(
    array(
        'summary_field'          => 'name',
        'summary_len'            => 100,
        'summary_ellipsis'       => ". . . ",
        'summary_snippet'        => 2,
        'summary_element_prefix' => '<em>',
        'summary_element_postfix' => '</em>'
    )
);

// --- Drop-down suggestion tracking ---
// Pass the request ID from a preceding drop-down suggestion request
// to correlate the search with the suggestion that triggered it.
$params->setCustomParam('from_request_id', '159851481919726888064081');

// --- Aggregation ---
// Count documents per cate_id value, sampling up to 10 groups.
$params->addAggregate(
    array(
        'groupKey'             => 'cate_id',
        'aggFun'               => 'count()',
        'range'                => '1',
        'aggSamplerThresHold'  => 1,
        'aggSamplerStep'       => 10,
        'maxGroup'             => 10
    )
);

// --- Ranking ---
$params->setFirstRankName('default');   // Rough sort expression
$params->setSecondRankName('default'); // Fine sort expression

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

// --- Query analyzer ---
$params->addQueryProcessor('Name of the query analyzer');

// --- Raw query ---
$params->setRawQuery("String");

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

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

Parameter reference

Sorting

addSort(field, order) adds a sort criterion. Multiple calls add multiple sort levels, applied in the order they are added. Use SearchParamsBuilder::SORT_DECREASE for descending order.

Distinct deduplication

addDistinct deduplicates results by a specified field. Key parameters:

ParameterDescription
keyThe field to deduplicate on
distTimesNumber of deduplication operations to perform
distCountMaximum number of results to keep per unique value
reservedWhether to keep or discard deduplicated documents ('true' or 'false')

Summary (snippet highlighting)

addSummary configures how matched terms are highlighted in search results. Key parameters:

ParameterDescription
summary_fieldThe field to highlight
summary_lenMaximum character length of the cropped snippet
summary_ellipsisString inserted between snippet fragments
summary_snippetMaximum number of snippet fragments to return
summary_element_prefixHTML tag inserted before each matched term
summary_element_postfixHTML tag inserted after each matched term

Aggregation

addAggregate groups results by a field and applies an aggregation function. Key parameters:

ParameterDescription
groupKeyThe field to group by
aggFunThe aggregation function, such as count()
maxGroupMaximum number of groups to return
aggSamplerThresHoldSampling threshold: documents beyond this count are sampled
aggSamplerStepSampling step size

Drop-down suggestion tracking

Pass the from_request_id custom parameter to associate a search request with a preceding drop-down suggestion request.

What's next