elasticsearch-dbapi

0.2.12 · active · verified Sat Apr 11

elasticsearch-dbapi (version 0.2.12) is an active Python library that provides a DBAPI (PEP-249) and SQLAlchemy dialect, enabling SQL access for query-only operations on Elasticsearch and OpenSearch clusters. It supports Elasticsearch 7.x, 8.x (via compatibility mode), and OpenSearch 2.x. Releases are made periodically to maintain compatibility and address issues.

Warnings

Install

Imports

Quickstart

Demonstrates connecting to an Elasticsearch/OpenSearch instance using the DBAPI interface, executing a basic SQL query, and listing available indices (tables). It highlights the critical environment variable for Elasticsearch 8.x compatibility.

import os
from es.elastic.api import connect

# IMPORTANT: For Elasticsearch 8.x, set ELASTIC_CLIENT_APIVERSIONING=1
# in your environment or before connecting to enable compatibility mode.
# os.environ['ELASTIC_CLIENT_APIVERSIONING'] = '1'

# Configure host and port. Adjust as necessary for your setup.
# For OpenSearch, a common port is 19200.
ES_HOST = os.environ.get('ES_HOST', 'localhost')
ES_PORT = int(os.environ.get('ES_PORT', 9200))

try:
    # Connect to Elasticsearch/OpenSearch via DBAPI
    conn = connect(host=ES_HOST, port=ES_PORT)
    curs = conn.cursor()

    # Execute a simple SQL query
    curs.execute("SELECT 1")
    result = curs.fetchall()
    print(f"Connection successful. Query 'SELECT 1' returned: {result}")

    # Example: List available tables (indices)
    curs.execute("SHOW TABLES")
    tables = curs.fetchall()
    print(f"First 5 available tables (indices): {tables[:5]}...")

    curs.close()
    conn.close()
    print("Successfully connected, queried, and closed connection.")
except Exception as e:
    print(f"Failed to connect or query Elasticsearch/OpenSearch: {e}")
    print("Please ensure your Elasticsearch/OpenSearch instance is running and accessible at ")
    print(f"'{ES_HOST}:{ES_PORT}'. For Elasticsearch 8.x, ensure ELASTIC_CLIENT_APIVERSIONING is set.")

view raw JSON →