A recuperação escalar é um recurso de indexação do OSS que usa metadados para localizar rapidamente objetos com condições específicas, como nome, ETag, classe de armazenamento, tamanho e hora da última modificação em buckets com grande volume de dados. Use o PHP SDK V2 para ative, consultar e desativar a recuperação escalar.
Precauções
O código de exemplo usa o ID da região China (Hangzhou)
cn-hangzhoue o endpoint público. Para acessar o OSS a partir de outros serviços da Alibaba Cloud na mesma região, use um endpoint interno. Para obter mais informações sobre o mapeamento entre regiões e endpoints, consulte Regiões e endpoints do OSS.O exemplo lê credenciais de acesso de variáveis de ambiente. Para outros métodos de configuração de credenciais, consulte Configure credenciais de acesso.
Inicialize um OSSClient para enviar solicitações ao OSS. O código fornecido crie esse cliente com as configurações padrão. Para outras opções de configuração, consulte Configure um cliente.
Código de exemplo
Ative o recurso de recuperação escalar
O código a seguir ativa a recuperação escalar para um bucket. Após a ativação, o OSS cria um índice de metadados para o bucket e todos os objetos existentes. O serviço passa então a rastrear novos objetos quase em tempo real e gera índices de metadados automaticamente.
<?php
// Import the autoloader file to ensure that dependency libraries can be 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 in which 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 the 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 in which 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 in which 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 an OpenMetaQueryRequest object to enable the scalar retrieval feature for the bucket.
$request = new Oss\Models\OpenMetaQueryRequest(
bucket: $bucket
);
// Execute the operation to enable the scalar retrieval feature.
$result = $client->openMetaQuery($request);
// Print the result of enabling the scalar 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 to debug or track requests.
);
Obter informações da biblioteca de índices de metadados
O código a seguir recupera as informações do índice de metadados de um bucket específico.
<?php
// Import the autoloader file to ensure that dependency libraries can be 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 in which 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 the 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 in which 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 in which 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 to debug or track requests.
'meta query status:' . var_export($result->metaQueryStatus, true) . PHP_EOL // The status of the metadata query feature, such as enabled or disabled.
);
Consultar objetos que atendem a condições especificadas
O código a seguir consulta objetos correspondentes aos critérios definidos e lista os resultados ordenados por um campo específico.
<?php
// Import the autoloader file to ensure that dependency libraries can be 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 in which 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 the 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 in which 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 in which 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 DoMetaQueryRequest object to perform a metadata query operation.
$request = new \AlibabaCloud\Oss\V2\Models\DoMetaQueryRequest(
bucket: $bucket,
metaQuery: new \AlibabaCloud\Oss\V2\Models\MetaQuery(
maxResults: 5, // The maximum number of results to return.
query: "{'Field': 'Size','Value': '1048576','Operation': 'gt'}", // Query condition: objects whose size is greater than 1 MB.
sort: 'Size', // Sort by object size.
order: \AlibabaCloud\Oss\V2\Models\MetaQueryOrderType::ASC, // Sort in ascending order.
aggregations: new \AlibabaCloud\Oss\V2\Models\MetaQueryAggregations( // Aggregate operation
aggregations: [
new \AlibabaCloud\Oss\V2\Models\MetaQueryAggregation(
field: 'Size', // The object size field.
operation: 'sum' // Aggregate operation: sum.
),
new \AlibabaCloud\Oss\V2\Models\MetaQueryAggregation(
field: 'Size', // The object size field.
operation: 'max' // Aggregate operation: maximum value.
),
]
)
)
);
// Perform the metadata query operation.
$result = $client->doMetaQuery($request);
// Print the result of the metadata query.
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 to debug or track requests.
'result:' . var_export($result, true) . PHP_EOL // The query result, which contains the matched objects and their aggregate data.
);
Desativar o recurso de recuperação escalar
O código a seguir desativa a recuperação escalar em um bucket específico.
<?php
// Import the autoloader file to ensure that dependency libraries can be 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 in which 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 the 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 in which 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 in which 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 to debug or track requests.
);
Referências
Para obter mais informações sobre a recuperação escalar, consulte Recuperação escalar.
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 para recuperação escalar, acesse o Exemplo no GitHub.