El SDK de Simple Log Service para Python permite ejecutar consultas SQL mediante la función Dedicated SQL para el análisis de registros a gran escala.
Requisitos previos
Simple Log Service está activado.
El SDK de Simple Log Service para Python está inicializado.
Información de contexto
Simple Log Service ofrece la función Dedicated SQL para mejorar las capacidades de análisis SQL y 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 operaciones execute_logstore_sql y execute_project_sql para usar la función Dedicated SQL.
execute_logstore_sql: ejecuta la función Dedicated SQL en un logstore específico. Esta operación admite la sintaxis SQL-92. La instrucción de consulta usa el formato
Search statement|Analytic statement, donde la parte analítica sigue la sintaxis estándar SQL-92.execute_project_sql: ejecuta la función Dedicated SQL en un proyecto específico. Esta operación admite la sintaxis 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 datos antes del análisis, se recomienda llamar a la operación execute_logstore_sql y especificar una instrucción de consulta en formato Search statement|Analytic statement para lograr una mayor eficiencia.
Código de ejemplo para usar la función Dedicated SQL
Descripción de la operación
-
Operación execute_logstore_sql
Llame a la operación execute_logstore_sql para usar la función Dedicated SQL. Cree una solicitud con el formato
res = client.execute_logstore_sql(project, logstoreName, from, to, query, powerSql). En la siguiente tabla se describen los parámetros de la solicitud.Parámetro
Tipo
Obligatorio
Ejemplo
Descripción
project_name
String
Sí
N/A
Nombre del proyecto.
Este valor se especifica al crear el cliente de Simple Log Service, por lo que no es necesario configurarlo nuevamente.
logstore_name
String
Sí
N/A
Nombre del logstore.
Este valor se especifica al crear el cliente de Simple Log Service, por lo que no es necesario configurarlo nuevamente.
from
Long
Sí
int(time.time() - 60)
Inicio del intervalo de tiempo de la consulta. El valor es una marca de tiempo UNIX que representa el número de segundos transcurridos desde la época (1 de enero de 1970, 00:00:00 UTC).
to
Long
Sí
int(time.time())
Fin del intervalo de tiempo de la consulta. El valor es una marca de tiempo UNIX que representa el número de segundos transcurridos desde la época (1 de enero de 1970, 00:00:00 UTC).
query
String
Sí
"* | select count(1) as cnt"
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 el número de filas de datos que se devolverán. Para obtener más información, consulte LIMIT clause.
powerSql
Boolean
No
True
Especifica si se debe usar la función Dedicated SQL. Para obtener más información, consulte High-performance fully accurate query and analysis (Dedicated SQL).
-
True: se usa la función Dedicated SQL.
-
False (predeterminado): se usa la función Standard SQL.
-
-
Operación execute_project_sql
Llame a la operación execute_project_sql para usar la función Dedicated SQL. Cree una solicitud con el formato
res = client.execute_project_sql(project, query, powerSql). En la siguiente tabla se describen los parámetros de la solicitud.Parámetro
Tipo
Obligatorio
Ejemplo
Descripción
project_name
String
Sí
aliyun-test-project
Nombre del proyecto.
Este valor se especifica al crear el cliente de Simple Log Service, por lo que no es necesario configurarlo nuevamente.
query
String
Sí
"select count(1) as cnt from %s where __time__ > %s" % (logstore_name, int(time.time() - 60))
Instrucción SQL. Debe especificar la condición de búsqueda 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 el número de filas de datos que se devolverán. Para obtener más información, consulte LIMIT clause.
powerSql
Boolean
No
True
Especifica si se debe usar la función Dedicated SQL. Para obtener más información, consulte High-performance fully accurate query and analysis (Dedicated SQL).
-
True: se usa la función Dedicated SQL.
-
False (predeterminado): se usa la función Standard SQL.
-
Código de ejemplo
El siguiente código de ejemplo muestra cómo usar la función Dedicated SQL. Para obtener más información, consulte aliyun-log-python-sdk.
# encoding: utf-8
from __future__ import print_function
import time
import os
from aliyun.log import *
def main():
# Specify a Simple Log Service endpoint.
endpoint = 'ap-southeast-1.log.aliyuncs.com'
# Configure environment variables. In this example, the AccessKey ID and AccessKey secret are obtained from environment variables.
access_key_id = os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID', '')
access_key = os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET', '')
# The name of the project.
project_name = 'aliyun-test-project'
# The name of the logstore.
logstore_name = 'aliyun-test-logstore'
# Create a Simple Log Service client.
client = LogClient(endpoint, access_key_id, access_key)
# Execute an SQL statement in the specified logstore.
print("===sample_execute_logstore_sql===")
res = client.execute_logstore_sql(project_name, logstore_name,
int(time.time() - 60),int(time.time()),
"* | select count(1) as cnt",True)
# Display the statistics about the analysis results.
res.log_print()
# The number of rows of log data that is processed.
print("processed_rows: %s" % res.get_processed_rows())
# The time that is consumed to execute the SQL statement.
print("elapsed_mills: %s" % res.get_elapsed_mills())
# Display whether an SQL statement is used.
print("has_sql: %s" % res.get_has_sql())
# The WHERE clause that precedes the vertical bar (|).
print("where_query: %s" % res.get_where_query())
# The SELECT statement that follows the vertical bar (|). The SELECT statement contains an aggregate function.
print("agg_query: %s" % res.get_agg_query())
# 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("cpu_sec: %s" % res.get_cpu_sec())
# The number of CPU cores that are used to execute the SQL statement after the Dedicated SQL feature is enabled.
print("cpu_cores: %s" % res.get_cpu_cores())
# Execute an SQL statement in the specified project.
print("===sample_execute_project_sql===")
res = client.execute_project_sql(project_name,"select count(1) as cnt from %s where __time__ > %s"
% (logstore_name, int(time.time() - 60)),True)
# Display the statistics about the analysis results.
res.log_print()
# The number of rows of log data that is processed.
print("processed_rows: %s" % res.get_processed_rows())
# The time that is consumed to execute the SQL statement.
print("elapsed_mills: %s" % res.get_elapsed_mills())
# Display whether an SQL statement is used.
print("has_sql: %s" % res.get_has_sql())
# The WHERE clause that precedes the vertical bar (|).
print("where_query: %s" % res.get_where_query())
# The SELECT statement that follows the vertical bar (|). The SELECT statement contains an aggregate function.
print("agg_query: %s" % res.get_agg_query())
# 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("cpu_sec: %s" % res.get_cpu_sec())
# The number of CPU cores that are used to execute the SQL statement after the Dedicated SQL feature is enabled.
print("cpu_cores: %s" % res.get_cpu_cores())
if __name__ == '__main__':
main()
Código de ejemplo para crear, modificar y consultar una instancia SQL
Una vez habilitada la función Dedicated SQL, cree una instancia SQL para especificar el número de CU. Ajuste la cantidad de CU para controlar los costos. Para obtener más información, consulte High-performance fully accurate query and analysis (Dedicated SQL).
El siguiente código de ejemplo muestra cómo crear, modificar y consultar una instancia SQL. Para obtener más información, consulte aliyun-log-python-sdk.
# encoding: utf-8
from __future__ import print_function
import time
import os
from aliyun.log import *
def main():
# The Simple Log Service endpoint. For more information, see Endpoints. In this example, the Simple Log Service endpoint for the China (Hangzhou) region is used. Replace the parameter value with the actual endpoint.
endpoint = 'ap-southeast-1.log.aliyuncs.com'
# Configure environment variables. In this example, the AccessKey ID and AccessKey secret are obtained from environment variables.
access_key_id = os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID', '')
access_key = os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET', '')
# The name of the project.
project_name = 'aliyun-test-project'
# The name of the logstore.
logstore_name = 'aliyun-test-logstore'
# Create a Simple Log Service client.
client = LogClient(endpoint, access_key_id, access_key)
# Create an SQL instance. You can specify the number of CUs for the SQL instance. Valid values: 0 to 1000.
print("===sample_create_sql_instance===")
res = client.create_sql_instance(project_name, 500)
res.log_print()
# Modify the configurations of the SQL instance. You can change the number of CUs for the SQL instance. Valid values: 0 to 1000.
print("===sample_update_sql_instance===")
res = client.update_sql_instance(project_name, 800)
res.log_print()
# Query the configurations of the SQL instance.
print("===sample_list_sql_instance===")
res = client.list_sql_instance(project_name)
res.log_print()
if __name__ == '__main__':
main()