La recherche scalaire est une fonctionnalité d'indexation d'OSS qui utilise les métadonnées des objets pour localiser rapidement ceux correspondant à des conditions spécifiques, telles que le nom de l'objet, l'ETag, la classe de stockage, la taille et la date de dernière modification, parmi un grand nombre d'objets dans un bucket. Vous pouvez utiliser le SDK PHP V2 pour activer, interroger et désactiver la recherche scalaire.
Précautions
L'exemple de code utilise l'ID de région Chine (Hangzhou)
cn-hangzhouet l'endpoint public. Pour accéder à OSS depuis d'autres services Alibaba Cloud dans la même région, utilisez un endpoint interne. Pour plus d'informations sur les correspondances entre régions et endpoints, consultez Régions et endpoints OSS.L'exemple de code lit les identifiants d'accès à partir des variables d'environnement. Pour d'autres méthodes de configuration des identifiants, consultez Configurer les identifiants d'accès.
Pour envoyer des requêtes OSS, vous devez initialiser un OSSClient. L'exemple de code crée un OSSClient avec les configurations par défaut. Pour d'autres méthodes de configuration du client, consultez Configurer un client.
Exemple de code
Activer la fonctionnalité de recherche scalaire
Le code suivant active la recherche scalaire pour un bucket. Une fois activée, OSS crée un index de métadonnées pour le bucket et tous les objets existants. OSS effectue ensuite un suivi incrémentiel en temps quasi réel des nouveaux objets et crée automatiquement des index de métadonnées pour ceux-ci.
<?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.
);
Obtenir les informations de la bibliothèque d'index de métadonnées
Le code suivant récupère les informations de l'index de métadonnées d'un bucket spécifié.
<?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.
);
Interroger les objets répondant à des conditions spécifiées
Le code suivant interroge les objets correspondant à des conditions spécifiées et liste les résultats triés selon un champ indiqué.
<?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.
);
Désactiver la fonctionnalité de recherche scalaire
Le code suivant désactive la recherche scalaire pour un bucket spécifié.
<?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.
);
Références
Pour plus d'informations sur la recherche scalaire, consultez Recherche scalaire.
Pour plus d'informations sur les opérations API relatives à l'indexation des données, consultez Indexation des données.
Pour l'exemple de code complet relatif à la recherche scalaire, consultez Exemple GitHub.