Connect to Elasticsearch with an SDK

You can use an official Elasticsearch client library to connect your application to Elasticsearch from code. This page shows how to install and initialize the client for each supported language.

Note

To get started without installing a client, work with Elasticsearch data in the Kibana Dev Tools Console, or send requests with curl. For curl examples, refer to the Elasticsearch API documentation.

You need the following:

The following steps show you how to set your endpoint and API key, install a client for your language, and verify the connection.

  1. Set environment variables

    Set your Elasticsearch endpoint and API key as environment variables:

    export ES_URL="YOUR_PROJECT_URL"
    export ES_API_KEY="YOUR_API_KEY"
    		
    1. For example, https://my-project.es.us-east-1.aws.elastic.cloud:443.
    $Env:ES_URL = "YOUR_PROJECT_URL"
    $Env:ES_API_KEY = "YOUR_API_KEY"
    		
    1. For example, https://my-project.es.us-east-1.aws.elastic.cloud:443.
  2. Install and initialize a client

    Install the client for your language. For a list of available clients, refer to Elasticsearch clients.

    pip install elasticsearch
    		

    For supported Python versions and other requirements, refer to the Python client documentation.

    npm install @elastic/elasticsearch
    npm install --save-dev typescript tsx
    npm pkg set type=module
    		

    For supported Node.js versions and other requirements, refer to the JavaScript client documentation.

    composer require elasticsearch/elasticsearch
    		

    For supported PHP versions and other requirements, refer to the PHP client documentation.

    bundle add elasticsearch
    		

    For supported Ruby versions and other requirements, refer to the Ruby client installation documentation.

    dotnet add package Elastic.Clients.Elasticsearch
    		

    For supported .NET versions and other requirements, refer to the .NET client documentation.

    In the generated build.gradle file, add the client dependency to the dependencies block and set mainClass in the application block:

    dependencies {
        implementation "co.elastic.clients:elasticsearch-java:VERSION"
    }
    
    application {
        mainClass = "quickstart.App"
    }
    		

    Replace VERSION with the version from the latest Java client release. For supported Java versions and other requirements, refer to the Java client documentation.

    go get github.com/elastic/go-elasticsearch/v9
    		

    For supported Go versions and other requirements, refer to the Go client installation documentation.

    After installation, initialize the client:

    import os
    from elasticsearch import Elasticsearch
    
    es = Elasticsearch(
        os.environ["ES_URL"],
        api_key=os.environ["ES_API_KEY"],
    )
    		
    import { Client } from "@elastic/elasticsearch";
    
    const es = new Client({
      node: process.env.ES_URL,
      auth: { apiKey: process.env.ES_API_KEY! },
    });
    		
    <?php
    
    require __DIR__ . "/vendor/autoload.php";
    
    use Elastic\Elasticsearch\ClientBuilder;
    
    $es = ClientBuilder::create()
        ->setHosts([getenv("ES_URL")])
        ->setApiKey(getenv("ES_API_KEY"))
        ->build();
    		
    require "elasticsearch"
    
    es = Elasticsearch::Client.new(
      url: ENV.fetch("ES_URL"),
      api_key: ENV.fetch("ES_API_KEY")
    )
    		
    using Elastic.Clients.Elasticsearch;
    using Elastic.Transport;
    
    var url = Environment.GetEnvironmentVariable("ES_URL")
        ?? throw new InvalidOperationException("ES_URL is not set.");
    var apiKey = Environment.GetEnvironmentVariable("ES_API_KEY")
        ?? throw new InvalidOperationException("ES_API_KEY is not set.");
    
    var settings = new ElasticsearchClientSettings(new Uri(url))
        .Authentication(new ApiKey(apiKey));
    var es = new ElasticsearchClient(settings);
    		
    package quickstart;
    
    import co.elastic.clients.elasticsearch.ElasticsearchClient;
    
    public class App {
        public static void main(String[] args) throws Exception {
            String serverUrl = System.getenv("ES_URL");
            String apiKey = System.getenv("ES_API_KEY");
    
            ElasticsearchClient es = ElasticsearchClient.of(b -> b
                .host(serverUrl)
                .apiKey(apiKey)
            );
        }
    }
    		
    package main
    
    import (
    	"log"
    	"os"
    
    	"github.com/elastic/go-elasticsearch/v9"
    )
    
    func main() {
    	es, err := elasticsearch.New(
    		elasticsearch.WithAddresses(os.Getenv("ES_URL")),
    		elasticsearch.WithAPIKey(os.Getenv("ES_API_KEY")),
    	)
    	if err != nil {
    		log.Fatal(err)
    	}
    }
    		
  3. Verify your connection

    Call the info API to confirm that your endpoint URL and API key work. A successful response includes the cluster name and version. The exact output depends on your client and your deployment.

    print(es.info())
    		
    console.log(await es.info());
    		
    echo $es->info()->asString();
    		
    puts es.info
    		
    var info = await es.InfoAsync();
    Console.WriteLine($"{info.ClusterName} {info.Version.Number}");
    		
    System.out.println(es.info());
    es._transport().close();
    		
    res, err := es.Info()
    if err != nil {
    	log.Fatal(err)
    }
    defer res.Body.Close()
    log.Println(res)
    		

Elasticsearch is up and running, and your application is connected. Next, learn how to ingest your own data in Ingest for search use cases.