All Products
Search
Document Center

Simple Log Service:Use an Elasticsearch SDK to access Simple Log Service

Last Updated:Sep 10, 2024

This topic describes how to use an Elasticsearch SDK to call the Elasticsearch-compatible API to analyze data in Simple Log Service.

Important

Alibaba Cloud has proprietary rights to the information in this topic. This topic describes the capabilities of Alibaba Cloud to interact with third-party services. The names of third-party companies and services are used only for reference.

Prerequisites

  • Data is collected to a Standard Logstore in Simple Log Service. For more information, see Data collection overview.

  • At least one field index is created. For more information, see Create indexes.

  • An AccessKey pair is created for the Resource Access Management (RAM) user, and the required permissions to query logs in Logstores are granted to the RAM user. For more information, see Grant permissions to a RAM user.

Usage notes

  • Elasticsearch SDKs can access the Elasticsearch-compatible API only if the version of Elasticsearch is 7.x.

  • If you query data without specifying @timestamp, the system queries data within the last 24 hours by default.

Parameters

Parameter

Description

hosts

The access address. Format: https://${Project name}.${Project endpoint}/es/. For more information, see Endpoints.

Important

Only HTTPS is supported.

Username

The username and password. Specify the AccessKey ID and AccessKey secret of an Alibaba Cloud account or a RAM user for Username and Password.

We recommend that you use the AccessKey pair of a RAM user that has the query permissions on the Logstore. You can use the permission assistant feature to grant permissions to the RAM user. For more information, see Configure the permission assistant feature. For more information about how to obtain an AccessKey pair, see AccessKey pair.

Password

Index

${Project name}.${Logstore name}

Examples

The following examples show how to use an Elasticsearch SDK to call the Elasticsearch-compatible API to analyze data in Simple Log Service. In this example, the etl-dev project, accesslog Logstore, and cn-huhehaote.log.aliyuncs.com endpoint are used.

Example of executing the curl command

curl -u ${ALIYUN_ACCESS_KEY_ID}:${ALIYUN_ACCESS_KEY_SECRET} "https://etl-dev.cn-huhehaote.log.aliyuncs.com/es/etl-dev.accesslog/_search?q=status:200"

Example of using Elasticsearch SDK for Python

  1. Install dependencies.

    pip install elasticsearch==7.10.0

  2. Run the following sample code:

    #!/bin/env python3
    import os
    import json
    import time
    from elasticsearch import Elasticsearch, helpers
    
    slsProject = "etl-dev"
    slsEndpoint = "cn-huhehaote.log.aliyuncs.com"
    slsLogstore = "accesslog"
    
    esHost = "https://%s.%s/es/" % (slsProject, slsEndpoint)
    esIndex = "%s.%s" % (slsProject, slsLogstore)
    
    # Obtain the AccessKey pair from environment variables.
    accessKeyId = os.environ['ALIYUN_ACCESS_KEY_ID']
    accessKeySecret = os.environ['ALIYUN_ACCESS_KEY_SECRET']
    
    esClient = Elasticsearch(hosts=esHost,
                    http_auth=(accessKeyId, accessKeySecret),
                       verify_certs=True, timeout=300)
    
    endTime = int(time.time()*1000)
    startTime = endTime - 3600*1000
    
    r = esClient.search(
        index=esIndex,
        body=   {
            "query": {
                "bool": {
                    "filter": [
                        {
                            "range": {
                                "@timestamp": {
                                    "gte": startTime,
                                    "lte": endTime,
                                    "format": "epoch_millis"
                                }
                            }
                        }
                    ]
                }
            }
         }
    )
    
    print(json.dumps(r, indent=4))

Example of using the Elasticsearch DSL

Elasticsearch provides the Query Domain-Specific Language (DSL) for searches. You can use the following method to access Simple Log Service by using the Elasticsearch DSL. This way, you do not need to manually assemble the DSL.

  1. Install dependencies.

    pip install elasticsearch-dsl==7.4.1
  2. Run the following sample code:

    #!/bin/env python3
    import os
    import json
    import time
    from elasticsearch import Elasticsearch, helpers
    from elasticsearch_dsl import Search, Q
    
    slsProject = "etl-dev"
    slsEndpoint = "cn-huhehaote.log.aliyuncs.com"
    slsLogstore = "accesslog"
    
    esHost = "https://%s.%s/es/" % (slsProject, slsEndpoint)
    esIndex = "%s.%s" % (slsProject, slsLogstore)
    
    # Obtain the AccessKey pair from environment variables.
    accessKeyId = os.environ['ALIYUN_ACCESS_KEY_ID']
    accessKeySecret = os.environ['ALIYUN_ACCESS_KEY_SECRET']
    
    esClient = Elasticsearch(hosts=esHost,
                    http_auth=(accessKeyId, accessKeySecret),
                       verify_certs=True, timeout=300)
    
    endTime = int(time.time()*1000)
    startTime = endTime - 3600*1000
    
    s = Search(using=esClient, index=esIndex) \
            .filter(Q("range", **{"@timestamp": {"gte": startTime, "lt": endTime, "format": "epoch_millis"}}))  \
            .query("match", request_method="GET") \
    
    response = s.execute()
    
    for hit in response:
        # request_method, host, and client_ip are logs fields in Simple Log Service.
        print(hit.request_method, hit.host, hit.client_ip)

Example of using Elasticsearch SDK for Go

package main

import (
	"context"
	"fmt"
	"os"
	"time"

	"github.com/olivere/elastic/v7"
)

func main() {
	// The following sample code shows how to use an Elasticsearch SDK to access the Elasticsearch-compatible API.
	slsProject := "etl-dev"
	slsLogstore := "accesslog"
	slsEndpoint := "cn-huhehaote.log.aliyuncs.com"

	accessKeyID := os.Getenv("ALIYUN_ACCESS_KEY_ID")
	accessKeySecret := os.Getenv("ALIYUN_ACCESS_KEY_SECRET")
	esHost := fmt.Sprintf("https://%s.%s:443/es", slsProject, slsEndpoint)
	esIndex := fmt.Sprintf("%s.%s", slsProject, slsLogstore)

	esClient, err := elastic.NewClient(
		elastic.SetURL(esHost),
		elastic.SetSniff(false),
		elastic.SetBasicAuth(accessKeyID, accessKeySecret), // Specify the username and password for basic authentication.
		elastic.SetHealthcheck(false), // Disable the health check feature.
	)
	if err != nil {
		panic(err)
	}

	termQuery := elastic.NewTermQuery("request_method", "GET")
	endTime := time.Now().Unix()
	startTime := endTime - 3600
	timeRangeQuery := elastic.NewRangeQuery("@timestamp").Gte(startTime).Lte(endTime)

	boolQuery := elastic.NewBoolQuery()
	boolQuery = boolQuery.Must(timeRangeQuery, termQuery)

	searchResult, err := esClient.Search().
		Index(esIndex).
		Query(boolQuery).
		From(0).Size(10).
		Pretty(true).
		Do(context.Background())
	if err != nil {
		panic(err)
	}

	//Output the result.
	for _, hit := range searchResult.Hits.Hits {
		fmt.Println(string(hit.Source))
	}
}

Example of using Elasticsearch SDK for Java

  1. Use the pom.xml file to introduce dependencies.

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
    
        <groupId>org.example</groupId>
        <artifactId>estest</artifactId>
        <version>1.0-SNAPSHOT</version>
    
        <properties>
            <maven.compiler.source>8</maven.compiler.source>
            <maven.compiler.target>8</maven.compiler.target>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        </properties>
        <dependencies>
            <dependency>
                <groupId>org.elasticsearch.client</groupId>
                <artifactId>elasticsearch-rest-high-level-client</artifactId>
                <version>7.10.1</version>
            </dependency>
            <dependency>
                <groupId>org.elasticsearch.client</groupId>
                <artifactId>elasticsearch-rest-client</artifactId>
                <version>7.10.1</version>
            </dependency>
        </dependencies>
    </project>
  2. Run the following sample code:

    package org.example;
    
    import org.apache.http.HttpHost;
    import org.apache.http.auth.AuthScope;
    import org.apache.http.auth.UsernamePasswordCredentials;
    import org.apache.http.client.CredentialsProvider;
    import org.apache.http.impl.client.BasicCredentialsProvider;
    import org.elasticsearch.action.search.SearchRequest;
    import org.elasticsearch.action.search.SearchResponse;
    import org.elasticsearch.client.RequestOptions;
    import org.elasticsearch.client.RestClient;
    import org.elasticsearch.client.RestClientBuilder;
    import org.elasticsearch.client.RestHighLevelClient;
    import org.elasticsearch.index.query.BoolQueryBuilder;
    import org.elasticsearch.index.query.MatchQueryBuilder;
    import org.elasticsearch.index.query.RangeQueryBuilder;
    import org.elasticsearch.search.builder.SearchSourceBuilder;
    
    import java.io.IOException;
    
    public class Main {
        public static void main(String[] args) throws IOException {
    
            String slsProject = "etl-dev";
            String slsLogstore = "accesslog";
            String slsEndpoint = "cn-huhehaote.log.aliyuncs.com";
    
            String schema = "https";
            String esHost = slsProject + "." +  slsEndpoint; // ${project}.${endpoint}
            int port = 443;
            String esIndex = slsProject + "." + slsLogstore; // ${project}.${logstore}
            String esPrefix = "/es/";
            String accessKeyId = System.getenv("ALIYUN_ACCESS_KEY_ID");
            String accessKeySecret = System.getenv("ALIYUN_ACCESS_KEY_SECRET");
    
            final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials(accessKeyId, accessKeySecret));
    
            RestClientBuilder builder = RestClient.builder(new HttpHost(esHost, port, schema)).setHttpClientConfigCallback(
                        httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
    
            // Set /es/ prefix
            builder.setPathPrefix(esPrefix);
            RestHighLevelClient client = new RestHighLevelClient(builder);
    
            // Query
            BoolQueryBuilder boolExpr= new BoolQueryBuilder();
    
            long endTime = System.currentTimeMillis();
            long startTime = endTime - 3600 * 1000;
            boolExpr.filter().add(new MatchQueryBuilder("request_method", "GET"));
            boolExpr.filter().add(new RangeQueryBuilder("@timestamp").gte(startTime).lte(endTime).format("epoch_millis"));
    
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    
            searchSourceBuilder.query(boolExpr);
            SearchRequest searchRequest = new SearchRequest(esIndex);
            searchRequest.source(searchSourceBuilder);
            SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
            System.out.println(searchResponse.toString());
    
            client.close();
        }
    }

Example of using Elasticsearch SDK for PHP

  1. Run the composer command to install the PHP plug-in.

    composer require elasticsearch/elasticsearch
  2. Run the following sample code:

    <?php
    
    require 'vendor/autoload.php';
    
    use Elasticsearch\ClientBuilder;
    
    $slsProject = 'etl-dev';
    $slsLogstore = 'accesslog';
    $slsEndpoint = 'cn-huhehaote.log.aliyuncs.com';
    
    $esHost = $slsProject . '.' . $slsEndpoint;
    $esIndex = $slsProject . '.' . $slsLogstore;
    
    $accessKeyId = getenv('ALIYUN_ACCESS_KEY_ID');
    $accessKeySecret = getenv('ALIYUN_ACCESS_KEY_SECRET');
    
    $hosts = [
        [
            'host' => $esHost,
            'port' => '443',
            'scheme' => 'https',
            'path' => '/es',
            'user' => $accessKeyId,
            'pass' => $accessKeySecret,
        ]
    ];
    
    $client = ClientBuilder::create()
        ->setHosts($hosts)
        ->build();
    
    $end Time = round(microtime(true) * 1000); // Unit: milliseconds.
    $startTime = $endTime - (3600 * 1000);
    
    
    $params = [
        'index' => $esIndex,
        'body'  => [
            'query' => [
                'bool' => [
                    'must' => [
                        'match' => [
                            'request_method' => 'GET'
                        ]
                    ],
                    'filter' => [
                        'range' => [
                            '@timestamp' => [
                                'gte' => $startTime,
                                'lte' => $endTime
                            ]
                        ]
                    ]
                ]
            ]
        ]
    ];
    
    $response = $client->search($params);
    
    print_r($response);