Todos os produtos
Search
Central de documentação

Object Storage Service:AISearch via OSS SDK for PHP 2.0

Última atualização: Jul 03, 2026

O AISearch localiza objetos rapidamente em grandes volumes de dados com base em condições como conteúdo semântico, metadados do OSS, metadados multimídia, ETags, tags e metadados personalizados para aumentar a eficiência. Este tópico descreve como usar o OSS SDK for PHP 2.0 com o AISearch.

Observações

  • Os códigos de exemplo deste tópico usam o ID da região cn-hangzhou, correspondente à região China (Hangzhou). Por padrão, um endpoint público acessa os recursos de um bucket. Para acessar os recursos do bucket a partir de outros serviços da Alibaba Cloud na mesma região, use um endpoint interno. Para obter mais informações sobre regiões e endpoints compatíveis, consulte Regiões e endpoints do OSS.

  • Neste tópico, as credenciais de acesso são obtidas de variáveis de ambiente. Para obter instruções sobre como configurar credenciais de acesso, consulte Seleção de produto.

  • Para iniciar uma solicitação com o OSS SDK for PHP, inicialize uma instância OSSClient. Neste exemplo, a criação da instância OSSClient usa as configurações padrão. Para saber como configurar uma instância OSSClient no OSS SDK for PHP 2.0, consulte Configurar uma instância OSSClient.

Exemplos

Ative o AISearch

O código a seguir ativa o recurso AISearch em um bucket.

<?php

// Include the autoload file to load dependencies.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Define and describe command-line parameters.
$optsdesc = [
    "region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // (Required) The region in which the bucket resides. 
    "endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // (Optional) The endpoint that other services can use to access OSS. 
    "bucket" => ['help' => 'The name of the bucket', 'required' => True], // (Required) The name of the bucket. 
];

// Convert the descriptions to a list of long options required by getopt.
// Add a colon (:) to the end of each parameter to indicate that a value is required.
$longopts = \array_map(function ($key) {
    return "$key:";
}, array_keys($optsdesc));

// Parse the command-line parameters.
$options = getopt("", $longopts);

// Check whether the required parameters are configured.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help']; // Obtain help information for the parameters.
        echo "Error: the following arguments are required: --$key, $help" . PHP_EOL;
        exit(1); // Exit the program if a required parameter is missing.
    }
}

// Assign the values parsed from the command-line parameters to the corresponding variables.
$region = $options["region"]; // The region in which the bucket resides.
$bucket = $options["bucket"]; // The name of the bucket.

// Load access credentials from environment variables.
// Use EnvironmentVariableCredentialsProvider to retrieve the AccessKey ID and AccessKey secret from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Use the default configuration of the SDK.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider); // Specify the credential provider.
$cfg->setRegion($region); // Specify the region in which the bucket resides.
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]); // Specify the endpoint if one is provided.
}

// Create an OSSClient instance.
$client = new Oss\Client($cfg);

// Enable the AISearch feature.
$request = new Oss\Models\OpenMetaQueryRequest($bucket,'semantic');
$result = $client->openMetaQuery($request);

printf(
   'status code:' . $result->statusCode . PHP_EOL .
   'request id:' . $result->requestId
);

Obtenha informações sobre a biblioteca de índice de metadados

O código a seguir obtém informações sobre a biblioteca de índice de metadados de um bucket.

<?php

// Include the autoload file to load dependencies.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Define and describe command-line parameters.
$optsdesc = [
    "region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // (Required) The region in which the bucket resides. 
    "endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // (Optional) The endpoint that other services can use to access OSS. 
    "bucket" => ['help' => 'The name of the bucket', 'required' => True], // (Required) The name of the bucket. 
];

// Convert the argument description to the long option format required by getopt.
// A colon (:) after each argument indicates that the argument requires a value.
$longopts = \array_map(function ($key) {
    return "$key:";
}, array_keys($optsdesc));

// Parse the command line arguments.
$options = getopt("", $longopts);

// Check whether required arguments are specified.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help']; // Obtain the help information of the argument.
        echo "Error: the following arguments are required: --$key, $help" . PHP_EOL;
        exit(1); // If a required argument is not specified, exit the program.
    }
}

// Extract values from the parsed arguments.
$region = $options["region"]; // The region where the bucket is located.
$bucket = $options["bucket"]; // The name of the bucket.

// Load the credential information from environment variables.
// Use EnvironmentVariableCredentialsProvider to read the Access Key ID and Access Key Secret from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Use the default configurations of the SDK.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider); // Set the credential provider.
$cfg->setRegion($region); // Set the region where the bucket is located.
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]); // If an endpoint is provided, set the endpoint.
}

// Create an OSS client instance.
$client = new Oss\Client($cfg);

// Create a GetMetaQueryStatusRequest object to obtain the metadata query status of the bucket.
$request = new Oss\Models\GetMetaQueryStatusRequest(
    bucket: $bucket
);

// Execute the operation to obtain the metadata query status.
$result = $client->getMetaQueryStatus($request);

// Print the result of obtaining the metadata query status.
printf(
    'status code:' . $result->statusCode . PHP_EOL . // The HTTP status code. For example, 200 indicates that the request is successful.
    'request id:' . $result->requestId . PHP_EOL .   // The request ID, which is used for debugging or request tracking.
    'meta query status:' . var_export($result->metaQueryStatus, true) . PHP_EOL // The status of the metadata query feature, such as enabled or disabled.
);

Consulte objetos que atendem a condições especificadas

O exemplo a seguir usa o recurso AISearch para consultar objetos que atendem a condições específicas e listar as informações desses objetos conforme o campo e o método de ordenação definidos.

<?php

// Import the autoloader file to ensure that dependency libraries are correctly loaded.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Define the description of command line arguments.
$optsdesc = [
    "region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // The region where the bucket is located. This parameter is required.
    "endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // The endpoint that other services can use to access OSS. This parameter is optional.
    "bucket" => ['help' => 'The name of the bucket', 'required' => True], // The name of the bucket. This parameter is required.
];

// Convert the argument description to the long option format required by getopt.
// A colon (:) after each argument indicates that the argument requires a value.
$longopts = \array_map(function ($key) {
    return "$key:";
}, array_keys($optsdesc));

// Parse the command line arguments.
$options = getopt("", $longopts);

// Check whether required arguments are specified.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help']; // Obtain the help information of the argument.
        echo "Error: the following arguments are required: --$key, $help" . PHP_EOL;
        exit(1); // If a required argument is not specified, exit the program.
    }
}

// Extract values from the parsed arguments.
$region = $options["region"]; // The region where the bucket is located.
$bucket = $options["bucket"]; // The name of the bucket.

// Load the credential information from environment variables.
// Use EnvironmentVariableCredentialsProvider to read the Access Key ID and Access Key Secret from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Use the default configurations of the SDK.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider); // Set the credential provider.
$cfg->setRegion($region); // Set the region where the bucket is located.
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]); // If an endpoint is provided, set the endpoint.
}

// Create an OSS client instance.
$client = new Oss\Client($cfg);

// Perform an AISearch query for objects that meet the specified conditions.
$request = new Oss\Models\DoMetaQueryRequest($bucket, new Oss\Models\MetaQuery(
    maxResults: 99,
    query: "Overlook the snow-covered forest",
    mediaTypes: new Oss\Models\MetaQueryMediaTypes('image'),
    simpleQuery: '{"Operation":"gt", "Field": "Size", "Value": "30"}',
), 'semantic');

$result = $client->doMetaQuery($request);
printf(
    'status code:' . $result->statusCode . PHP_EOL .
    'request id:' . $result->requestId . PHP_EOL .
    'result:' . var_export($result, true)
);

Desative o recurso AISearch

O código a seguir desativa o recurso AISearch em um bucket específico.

<?php

// Import the autoloader file to ensure that dependency libraries are correctly loaded.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Define the description of command line arguments.
$optsdesc = [
    "region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // The region where the bucket is located. This parameter is required.
    "endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // The endpoint that other services can use to access OSS. This parameter is optional.
    "bucket" => ['help' => 'The name of the bucket', 'required' => True], // The name of the bucket. This parameter is required.
];

// Convert the argument description to the long option format required by getopt.
// A colon (:) after each argument indicates that the argument requires a value.
$longopts = \array_map(function ($key) {
    return "$key:";
}, array_keys($optsdesc));

// Parse the command line arguments.
$options = getopt("", $longopts);

// Check whether required arguments are specified.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help']; // Obtain the help information of the argument.
        echo "Error: the following arguments are required: --$key, $help" . PHP_EOL;
        exit(1); // If a required argument is not specified, exit the program.
    }
}

// Extract values from the parsed arguments.
$region = $options["region"]; // The region where the bucket is located.
$bucket = $options["bucket"]; // The name of the bucket.

// Load the credential information from environment variables.
// Use EnvironmentVariableCredentialsProvider to read the Access Key ID and Access Key Secret from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Use the default configurations of the SDK.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider); // Set the credential provider.
$cfg->setRegion($region); // Set the region where the bucket is located.
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]); // If an endpoint is provided, set the endpoint.
}

// Create an OSS client instance.
$client = new Oss\Client($cfg);

// Create a CloseMetaQueryRequest object to disable the retrieval feature for the bucket.
$request = new \AlibabaCloud\Oss\V2\Models\CloseMetaQueryRequest(
    bucket: $bucket
);

// Execute the operation to disable the retrieval feature.
$result = $client->closeMetaQuery($request);

// Print the result of disabling the retrieval feature.
printf(
    'status code:' . $result->statusCode . PHP_EOL . // The HTTP status code. For example, 200 indicates that the request is successful.
    'request id:' . $result->requestId . PHP_EOL     // The request ID, which is used for debugging or request tracking.
);

Referências

  • Para obter mais informações sobre as operações do AISearch, consulte Pesquisa vetorial.

  • Para obter mais informações sobre as operações de API para indexação de dados, consulte Indexação de dados.

  • Para visualizar o código de exemplo completo do AISearch, acesse o exemplo no GitHub.