File size: 1,347 Bytes
4cbe4e9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import os
import logging
from elasticsearch import Elasticsearch, ConnectionError, AuthenticationException

# Configure logging at the application level
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)

# Load environment variables
ES_CLIENT_URL = os.getenv("ELASTICSEARCH_HOSTS")

class ElasticsearchClientError(Exception):
    """Custom exception for Elasticsearch client errors."""
    pass

def get_es_client() -> Elasticsearch:
    """
    Establish connection to Elasticsearch and return the client instance.
    Raises ElasticsearchClientError if the connection cannot be established.
    """
    
    try:
        print("es client", ES_CLIENT_URL)
        # Initialize Elasticsearch client
        es_client = Elasticsearch(
            hosts=[ES_CLIENT_URL],  
        )

        # Verify connection
        if not es_client.ping():
            error_message = "Elasticsearch cluster is not reachable!"
            logger.error(error_message)
            raise ElasticsearchClientError(error_message)

        logger.info("Successfully connected to Elasticsearch")
        return es_client

    except (ConnectionError, AuthenticationException) as e:
        error_message = f"Elasticsearch connection error: {e}"
        logger.error(error_message)
        raise ElasticsearchClientError(error_message) from e