Utilice Simple Log Service SDK for PHP para ejecutar consultas SQL mediante la función Dedicated SQL.
Requisitos previos
Simple Log Service está activado. Activar Simple Log Service.
-
Se creó y se obtuvo un par de AccessKey. Para obtener más información, consulte AccessKey pair.
El par de AccessKey de una cuenta de Alibaba Cloud tiene permisos sobre todas las operaciones de API. Usar estas credenciales para ejecutar operaciones en Simple Log Service representa un riesgo alto de seguridad. Se recomienda utilizar un usuario de Resource Access Management (RAM) para invocar las operaciones de API o realizar tareas habituales de operación y mantenimiento. Para crear un usuario de RAM, inicie sesión en la consola de RAM. Asegúrese de que el usuario de RAM tenga los permisos de administración sobre los recursos de Simple Log Service. Para obtener más información, consulte Create a RAM user and grant permissions.
Simple Log Service SDK for PHP está instalado. Para obtener más información, consulte Install the Log Service PHP SDK.
Contexto
La función Dedicated SQL mejora las capacidades de análisis SQL y puede procesar cientos de miles de millones de registros de datos. Para obtener más información, consulte High-performance fully accurate query and analysis (Dedicated SQL).
Simple Log Service proporciona las siguientes operaciones para la función Dedicated SQL:
Aliyun_Log_Models_LogStoreSqlRequest: ejecuta consultas de Dedicated SQL en un logstore específico. Esta operación admite la sintaxis estándar SQL-92. La instrucción de consulta utiliza el formato
Search statement|Analytic statement, donde la instrucción analítica sigue la sintaxis estándar SQL-92.Aliyun_Log_Models_ProjectSqlRequest: ejecuta consultas de Dedicated SQL en un proyecto específico. Esta operación admite la sintaxis estándar SQL-92. Debe especificar una condición de filtro y un intervalo de tiempo en la cláusula WHERE de la instrucción SQL.
Para filtrar los datos antes del análisis, se recomienda invocar la operación Aliyun_Log_Models_LogStoreSqlRequest y especificar una instrucción de consulta con el formato Search statement|Analytic statement. Esto mejora la eficiencia del análisis.
Código de ejemplo
A continuación se muestra un código de ejemplo sobre cómo usar la función Dedicated SQL. Para obtener más información, consulte Alibaba Cloud Simple Log Service SDK for PHP.
<?PHP
require_once realpath(dirname(__FILE__) . './aliyun-log-php-sdk-master/Log_Autoload.php');
class test
{
public static function main()
{
// The Simple Log Service endpoint. In this example, the Simple Log Service endpoint for the China (Hangzhou) region is used. Replace the parameter value with the actual endpoint.
$endpoint = 'cn-hangzhou.log.aliyuncs.com';
// In this example, the AccessKey ID and AccessKey secret are obtained from environment variables.
$accessKeyId = getenv('ALIBABA_CLOUD_ACCESS_KEY_ID');
$accessKey = getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET');
// The name of the project.
$project = 'aliyun-test-project';
// The name of the Logstore.
$logstore = 'aliyun-test-logstore';
// The Security Token Service (STS) token.
$token = '';
// Create a Simple Log Service client.
$client = new Aliyun_Log_Client($endpoint, $accessKeyId, $accessKey, $token);
// Execute an SQL statement in the specified Logstore.
$from = time() - 3600;
$to = time();
$query = "* | select count(0)";
$topic = "";
$request = new Aliyun_Log_Models_LogStoreSqlRequest($project, $logstore, $from, $to, $query, true);
try {
$response = $client->executeLogStoreSql($request);
foreach ($response->getLogs() as $log) {
print $log->getTime() . "\t";
foreach ($log->getContents() as $key => $value) {
print $key . ":" . $value . "\t";
}
print "\n";
}
// Display the statistics about the analysis results.
// The number of lines of log data that is processed.
print "proccesedRows:" . $response->getProcessedRows() . "\n";
// The time that is required to execute the SQL statement.
print "elapsedMilli:" . $response->getElapsedMilli() . "\n";
// The CPU time that is consumed to execute the SQL statement after the Dedicated SQL feature is enabled. Unit: seconds. You are charged for the Dedicated SQL feature based on the CPU time. For more information, see the topics that are related to billable items.
print "cpuSec:" . $response->getCpuSec() . "\n";
// The number of CPU cores that are used to execute the SQL statement after the Dedicated SQL feature is enabled.
print "cpuCores:" . $response->getCpuCores() . "\n";
} catch (Aliyun_Log_Exception $ex) {
logVarDump($ex);
} catch (Exception $ex) {
logVarDump($ex);
}
// Execute an SQL statement in the specified project.
$query = "select count(0) from gs-api where __time__ > to_unixtime(now()) - 300 and __time__ < to_unixtime(now())";
$request = new Aliyun_Log_Models_ProjectSqlRequest($project, $query, True);
try {
$response = $client->executeProjectSql($request);
#$response = $client->getProjectLogs($request);
foreach ($response->getLogs() as $log) {
print $log->getTime() . "\t";
foreach ($log->getContents() as $key => $value) {
print $key . ":" . $value . "\t";
}
print "\n";
}
// Display the statistics about the analysis results.
// The number of lines of log data that is processed.
print "proccesedRows:" . $response->getProcessedRows() . "\n";
// The time that is required to execute the SQL statement.
print "elapsedMilli:" . $response->getElapsedMilli() . "\n";
// The CPU time that is consumed to execute the SQL statement after the Dedicated SQL feature is enabled. Unit: seconds. You are charged for the Dedicated SQL feature based on the CPU time. For more information, see the topics that are related to billable items.
print "cpuSec:" . $response->getCpuSec() . "\n";
// The number of CPU cores that are used to execute the SQL statement after the Dedicated SQL feature is enabled.
print "cpuCores:" . $response->getCpuCores() . "\n";
print "requestId:" . $response->getRequestId() . "\n";
} catch (Aliyun_Log_Exception $ex) {
logVarDump($ex);
} catch (Exception $ex) {
logVarDump($ex);
}
}
}
test::main();
-
Operación Aliyun_Log_Models_LogStoreSqlRequest
Invoque la operación Aliyun_Log_Models_LogStoreSqlRequest para usar la función Dedicated SQL. El formato de la solicitud es a continuación:
$from = time()-3600; $to = time(); $query = "* | select count(0)"; $topic = ""; $request = new Aliyun_Log_Models_LogStoreSqlRequest($project,$logstore,$from,$to,$topic,$query,$powerSql);En la siguiente tabla se describen los parámetros.
Parámetro
Tipo
Obligatorio
Ejemplo
Descripción
$project
String
Sí
N/A
Nombre del proyecto. Se especifica al crear el cliente de Simple Log Service. No es necesario configurarlo de nuevo.
$logstore
String
Sí
N/A
Nombre del logstore. Se especifica al crear el cliente de Simple Log Service. No es necesario configurarlo de nuevo.
$from
Long
Sí
time()-3600
Inicio del intervalo de tiempo de la consulta. El valor es una marca de tiempo UNIX que representa los segundos transcurridos desde el 1 de enero de 1970 a las 00:00:00 UTC.
$to
Long
Sí
time()
Fin del intervalo de tiempo de la consulta. El valor es una marca de tiempo UNIX que representa los segundos transcurridos desde el 1 de enero de 1970 a las 00:00:00 UTC.
$topic
String
No
topic-test
Tema de los registros.
$query
String
Sí
"* | select count(method)"Instrucción de consulta. Formato:
Search statement|Analytic statement. Para obtener más información, consulte Syntax.De forma predeterminada, Simple Log Service devuelve 100 filas de datos. Use una cláusula LIMIT para especificar la cantidad de filas de datos que se devuelven. Para obtener más información, consulte LIMIT clause.
$powerSql
Boolean
No
true
Indica si se usa la función Dedicated SQL. Para obtener más información, consulte High-performance fully accurate query and analysis (Dedicated SQL). Valores válidos:
-
true: usa la función Dedicated SQL.
-
false (valor predeterminado): usa la función Standard SQL.
-
-
Operación Aliyun_Log_Models_ProjectSqlRequest
Invoque la operación Aliyun_Log_Models_ProjectSqlRequest para usar la función Dedicated SQL. El formato de la solicitud es a continuación:
$query = "select count(0) from sls_operation_log where __time__ > to_unixtime(now()) - 300 and __time__ < to_unixtime(now())"; $request = new Aliyun_Log_Models_ProjectSqlRequest($project,$query,$powerSql);En la siguiente tabla se describen los parámetros.
Parámetro
Tipo
Obligatorio
Ejemplo
Descripción
$project
String
Sí
N/A
Nombre del proyecto. Se especifica al crear el cliente de Simple Log Service. No es necesario configurarlo de nuevo.
$query
String
Sí
" select count(method) from sls_operation_log where __time__ > to_unixtime(now()) - 300 and __time__ < to_unixtime(now())"Instrucción SQL. Debe especificar la condición de búsqueda y el intervalo de tiempo en la cláusula WHERE de la instrucción SQL.
De forma predeterminada, Simple Log Service devuelve 100 filas de datos. Use una cláusula LIMIT para especificar la cantidad de filas de datos que se devuelven. Para obtener más información, consulte LIMIT clause.
$powerSql
Boolean
No
true
Indica si se usa la función Dedicated SQL. Para obtener más información, consulte High-performance fully accurate query and analysis (Dedicated SQL). Valores válidos:
-
true: usa la función Dedicated SQL.
-
false (valor predeterminado): usa la función Standard SQL.
-