Todos os produtos
Search
Central de documentação

Simple Log Service:Use o Simple Log Service SDK for Java para gerenciar índices

Última atualização: Jul 03, 2026

Um índice é uma estrutura de armazenamento invertida que mapeia palavras-chave a linhas de dados para permitir consultas rápidas, semelhante a um catálogo de dados. Você só pode consultar e analisar dados de log após configurar os índices. Este tópico fornece exemplos de código para criar, modificar, consultar e excluir índices com o Simple Log Service SDK for Java.

Pré-requisitos

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 os endpoints compatíveis com o Simple Log Service, consulte Endpoint.

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 criação de índices

Gerencie índices diretamente no console do Simple Log Service. Para mais informações, consulte Criar índices.

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

import com.aliyun.openservices.log.Client;
import com.aliyun.openservices.log.common.Index;
import com.aliyun.openservices.log.exception.LogException;
public class CreateIndex {
    public static void main(String[] args) throws LogException {
        // This example obtains the AccessKey ID and AccessKey secret from environment variables.
        String accessId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
        String accessKey = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
        // Specify the project name.
        String projectName = "ali-test-project";
        // Specify the Logstore name.
        String logstoreName = "ali-test-logstore";
        // Set the endpoint of Simple Log Service. This example uses the endpoint of the China (Hangzhou) region. Replace the value with the actual endpoint.
        String host = "https://cn-hangzhou.log.aliyuncs.com";
        // Create a Simple Log Service client.
        Client client = new Client(host, accessId, accessKey);
        try {
            // Define the index.
            // Before you create an index, you must plan the full-text and field index configurations. In this example, a full-text index is enabled and a field index is created for the request_method and status fields.
            String logstoreindex = "{\"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}";
            Index index = new Index();
            System.out.println("ready to create index");
            index.FromJsonString(logstoreindex);
            client.CreateIndex(projectName, logstoreName, index);
            System.out.println(String.format("create index for %s success", logstoreName));
        } catch (LogException e) {
            System.out.println("LogException e :" + e.toString());
            System.out.println("error code :" + e.GetErrorCode());
            System.out.println("error message :" + e.GetErrorMessage());
            throw e;
        }
    }
}

Resultado esperado:

ready to create index
create index for ali-test-logstore success

Exemplo de código para modificação de índices

Também é possível gerenciar índices no console do Simple Log Service. Consulte Criar índices para mais detalhes.

O trecho a seguir modifica um índice existente. Neste cenário, mantêm-se a indexação de texto completo e a indexação dos campos request_method e status, alterando-se o parâmetro caseSensitive para True no campo request_method. O exemplo utiliza o log bruto como referência.

import com.aliyun.openservices.log.Client;
import com.aliyun.openservices.log.common.Index;
import com.aliyun.openservices.log.exception.LogException;
public class UpdateIndex {
    public static void main(String[] args) throws LogException {
        // This example obtains the AccessKey ID and AccessKey secret from environment variables.
        String accessId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
        String accessKey = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
        // Specify the project name.
        String projectName = "ali-test-project";
        // Specify the Logstore name.
        String logstoreName = "ali-test-logstore";
        // Set the endpoint of Simple Log Service. This example uses the endpoint of the China (Hangzhou) region. Replace the value with the actual endpoint.
        String host = "https://cn-hangzhou.log.aliyuncs.com";
        // Create a Simple Log Service client.
        Client client = new Client(host, accessId, accessKey);
        try {
            // Update the index.
            String logstoreindex = "{\"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}";
            Index index = new Index();
            System.out.println("ready to update index");
            index.FromJsonString(logstoreindex);
            client.UpdateIndex(projectName, logstoreName, index);
            System.out.println(String.format("update index for %s success", logstoreName));
        } catch (LogException e) {
            System.out.println("LogException e :" + e.toString());
            System.out.println("error code :" + e.GetErrorCode());
            System.out.println("error message :" + e.GetErrorMessage());
            throw e;
        }
    }
}

Resultado esperado:

ready to update index
update index for ali-test-logstore success

Exemplo de código para consulta de índices

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

import com.aliyun.openservices.log.Client;
import com.aliyun.openservices.log.common.Index;
import com.aliyun.openservices.log.exception.LogException;
import com.aliyun.openservices.log.response.GetIndexResponse;
public class ListIndex {
    public static void main(String[] args) throws LogException {
        // This example obtains the AccessKey ID and AccessKey secret from environment variables.
        String accessId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
        String accessKey = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
        // Specify the project name.
        String projectName = "ali-test-project";
        // Specify the Logstore name.
        String logstoreName = "ali-test-logstore";
        // Set the endpoint of Simple Log Service. This example uses the endpoint of the China (Hangzhou) region. Replace the value with the actual endpoint.
        String host = "https://cn-hangzhou.log.aliyuncs.com";
        // Create a Simple Log Service client.
        Client client = new Client(host, accessId, accessKey);
        try {
            Index index = new Index();
            System.out.println("ready to get index");
            GetIndexResponse response = client.GetIndex(projectName, logstoreName);
            index = response.GetIndex();
            // Print the index configuration.
            System.out.println("The index is: " + index.ToJsonString());
            System.out.println(String.format("get index for %s success", logstoreName));
        } catch (LogException e) {
            System.out.println("LogException e :" + e.toString());
            System.out.println("error code :" + e.GetErrorCode());
            System.out.println("error message :" + e.GetErrorMessage());
            throw e;
        }
    }
}

Resultado esperado:

ready to get index
The index is: {"log_reduce":false,"line":{"caseSensitive":false,"chn":false,"token":[","," ","'","\"",";","=","(",")","[","]","{","}","?","@","&","<",">","/",":","\n","\t","\r"]},"keys":{"request_method":{"doc_value":true,"caseSensitive":true,"chn":false,"alias":"","type":"text","token":[","," ","'","\"",";","=","(",")","[","]","{","}","?","@","&","<",">","/",":","\n","\t","\r"]},"status":{"doc_value":true,"alias":"","type":"long"}},"ttl":30,"max_text_len":2048}
get index for ali-test-logstore success

Exemplo de código para exclusão de índices

Use o código a seguir para excluir o índice de um Logstore específico.

import com.aliyun.openservices.log.Client;
import com.aliyun.openservices.log.exception.LogException;
public class DeleteIndex {
    public static void main(String[] args) throws LogException {
        // This example obtains the AccessKey ID and AccessKey secret from environment variables.
        String accessId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
        String accessKey = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
        // Specify the project name.
        String projectName = "ali-test-project";
        // Specify the Logstore name.
        String logstoreName = "ali-test-logstore";
        // Set the endpoint of Simple Log Service. This example uses the endpoint of the China (Hangzhou) region. Replace the value with the actual endpoint.
        String host = "https://cn-hangzhou.log.aliyuncs.com";
        // Create a Simple Log Service client.
        Client client = new Client(host, accessId, accessKey);
        try {
            System.out.println("ready to delete index");
            client.DeleteIndex(projectName, logstoreName);
            System.out.println(String.format("delete index for %s success", logstoreName));
        } catch (LogException e) {
            System.out.println("LogException e :" + e.toString());
            System.out.println("error code :" + e.GetErrorCode());
            System.out.println("error message :" + e.GetErrorMessage());
            throw e;
        }
    }
}

Resultado esperado:

ready to delete index
delete index for ali-test-logstore success

Referências