Todos os produtos
Search
Central de documentação

Simple Log Service:Gerenciar índices com o Simple Log Service SDK for Python

Última atualização: Sep 11, 2026

Um índice é uma estrutura de armazenamento invertida que mapeia palavras-chave a ponteiros lógicos para os dados reais, o que permite consultas rápidas por palavra-chave. Configure índices antes de consultar e analisar dados de log. Este tópico fornece exemplos de código para criar, modificar, consultar e excluir índices com o Simple Log Service SDK for Python.

Pré-requisitos

  • O Simple Log Service SDK for Python está initialized.

Precauções

Este exemplo usa o endpoint público do Simple Log Service na região China (Hangzhou). Endpoint: https://cn-hangzhou.log.aliyuncs.com.

Para acessar o Simple Log Service a partir de outros serviços da Alibaba Cloud na mesma região do projeto, use o endpoint interno do Simple Log Service: https://cn-hangzhou-intranet.log.aliyuncs.com.

Para obter mais informações sobre as regiões e endpoints compatíveis com o Simple Log Service, consulte Endpoint.

Faturamento

Logstores no modo de pagamento por dados ingeridos

Logstores no modo de pagamento por recurso

Log bruto

body_bytes_sent:1750
host:www.example.com
http_referer:www.example.com
http_user_agent:Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_6; it-it) AppleWebKit/533.20.25 (KHTML, like Gecko) Version/5.0.4 Safari/533.20.27
http_x_forwarded_for:203.0.XX.XX
remote_addr:203.0.XX.XX
remote_user:p288
request_length:13741
request_method:GET
request_time:71
request_uri:/request/path-1/file-1
http_code:200
time_local:11/Aug/2021:06:52:27
upstream_response_time:0.66

Exemplo de código para criar índices

Também é possível gerenciar índices no console do Simple Log Service. Para mais informações, consulte Crie índices.

O código abaixo cria índices com indexação de texto completo e de campo ativadas para os campos request_method e status. O exemplo baseia-se no log bruto.

from aliyun.log import LogClient, IndexConfig
import os
# This example retrieves the AccessKey ID and AccessKey secret from environment variables.
accessKeyId = os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID', '')
accessKey = os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET', '')
# The service endpoint for Simple Log Service. This example uses the endpoint for the China (Hangzhou) region. Replace it with your actual endpoint.
endpoint = "cn-hangzhou.log.aliyuncs.com"
# Create a Simple Log Service client.
client = LogClient(endpoint, accessKeyId, accessKey)
# The Project name.
project_name = "ali-test-project"
# The Logstore name.
logstore_name = "ali-test-logstore"
if __name__ == '__main__':
    # Before you create an index, you must plan the configurations for full-text indexing and field indexing. This example enables full-text indexing and field indexing for the request_method and status fields.
    logstore_index = {'line': {
        'token': [',', ' ', "'", '"', ';', '=', '(', ')', '[', ']', '{', '}', '?', '@', '&', '<', '>', '/', ':', '\n',
                  '\t',
                  '\r'], 'caseSensitive': False, 'chn': False}, 'keys': {'request_method': {'type': 'text',
                                                                                 'token': [',', ' ', "'", '"', ';', '=',
                                                                                           '(', ')', '[', ']', '{', '}',
                                                                                           '?', '@', '&', '<', '>', '/',
                                                                                           ':', '\n', '\t', '\r'],
                                                                                 'caseSensitive': False, 'alias': '',
                                                                                 'doc_value': True, 'chn': False},
                                                                         'status': {'type': 'long', 'alias': '',
                                                                                'doc_value': True}},
        'log_reduce': False,
        'max_text_len': 2048}
    print("ready to create index")
    index_config = IndexConfig()
    index_config.from_json(logstore_index)
    client.create_index(project_name, logstore_name, index_config)
    print("create index success ")

Resultados esperados:

ready to create index
create index success

Exemplo de código para modificar índices

Também é possível gerenciar índices no console do Simple Log Service. Para mais informações, consulte Crie índices.

O código abaixo modifica índices ao definir caseSensitive como True para o campo request_method. A indexação de texto completo e de campo para request_method e status permanece ativada. O exemplo baseia-se no log bruto.

from aliyun.log import LogClient, IndexConfig
import os
# This example retrieves the AccessKey ID and AccessKey secret from environment variables.
accessKeyId = os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID', '')
accessKey = os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET', '')
# The service endpoint for Simple Log Service. This example uses the endpoint for the China (Hangzhou) region. Replace it with your actual endpoint.
endpoint = "cn-hangzhou.log.aliyuncs.com"
# Create a Simple Log Service client.
client = LogClient(endpoint, accessKeyId, accessKey)
# The Project name.
project_name = "ali-test-project"
# The Logstore name.
logstore_name = "ali-test-logstore"
if __name__ == '__main__':
    # Set the request_method field to be case-sensitive.
    logstore_index = {'line': {
        'token': [',', ' ', "'", '"', ';', '=', '(', ')', '[', ']', '{', '}', '?', '@', '&', '<', '>', '/', ':', '\n',
                  '\t',
                  '\r'], 'caseSensitive': False, 'chn': False}, 'keys': {'request_method': {'type': 'text',
                                                                                 'token': [',', ' ', "'", '"', ';', '=',
                                                                                           '(', ')', '[', ']', '{', '}',
                                                                                           '?', '@', '&', '<', '>', '/',
                                                                                           ':', '\n', '\t', '\r'],
                                                                                 'caseSensitive': True, 'alias': '',
                                                                                 'doc_value': True, 'chn': False},
                                                                         'status': {'type': 'long', 'alias': '',
                                                                                'doc_value': True}},
        'log_reduce': False,
        'max_text_len': 2048}
    print("ready to update index")
    index_config = IndexConfig()
    index_config.from_json(logstore_index)
    client.update_index(project_name, logstore_name, index_config)
    print("update index success ")

Resultados esperados:

ready to update index
update index success

Exemplo de código para consultar índices

O código abaixo recupera a configuração de índice de um Logstore específico.

from aliyun.log import LogClient, IndexConfig
import os
# This example retrieves the AccessKey ID and AccessKey secret from environment variables.
accessKeyId = os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID', '')
accessKey = os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET', '')
# The service endpoint for Simple Log Service. This example uses the endpoint for the China (Hangzhou) region. Replace it with your actual endpoint.
endpoint = "cn-hangzhou.log.aliyuncs.com"
# Create a Simple Log Service client.
client = LogClient(endpoint, accessKeyId, accessKey)
# The Project name.
project_name = "ali-test-project"
# The Logstore name.
logstore_name = "ali-test-logstore"
if __name__ == '__main__':
    # Get the index configuration.
    print("ready to list index")
    res = client.get_index_config(project_name, logstore_name)
    print("The index config is :%s" % res.get_index_config().to_json())
    print("list index success ")

Resultados esperados:

ready to list index
The index config is :{'line': {'token': [',', ' ', "'", '"', ';', '=', '(', ')', '[', ']', '{', '}', '?', '@', '&', '<', '>', '/', ':', '\n', '\t', '\r'], 'caseSensitive': False, 'chn': False}, 'keys': {'request_method': {'type': 'text', 'token': [',', ' ', "'", '"', ';', '=', '(', ')', '[', ']', '{', '}', '?', '@', '&', '<', '>', '/', ':', '\n', '\t', '\r'], 'caseSensitive': True, 'alias': '', 'doc_value': True, 'chn': False}, 'status': {'type': 'long', 'alias': '', 'doc_value': True}}, 'log_reduce': False, 'max_text_len': 2048}
list index success

Exemplo de código para excluir índices

O código abaixo exclui o índice de um Logstore específico.

from aliyun.log import LogClient, IndexConfig
import os
# This example retrieves the AccessKey ID and AccessKey secret from environment variables.
accessKeyId = os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID', '')
accessKey = os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET', '')
# The service endpoint for Simple Log Service. This example uses the endpoint for the China (Hangzhou) region. Replace it with your actual endpoint.
endpoint = "cn-hangzhou.log.aliyuncs.com"
# Create a Simple Log Service client.
client = LogClient(endpoint, accessKeyId, accessKey)
# The Project name.
project_name = "ali-test-project"
# The Logstore name.
logstore_name = "ali-test-logstore2"
if __name__ == '__main__':
    # Delete the index.
    print("ready to delete index")
    client.delete_index(project_name, logstore_name)
    print("delete index success ")

Resultados esperados:

ready to delete index
delete index success

Referências