Is it possible to use starlette framwork to interact with elasticsearch?

Viewed 29

I am facing difficulty in accessing the elasticsearch index using starlette framework

My main.py is

from urllib.request import Request
from webbrowser import get
from elasticsearch import Elasticsearch, helpers
from starlette.applications import Starlette
from starlette.routing import Route
import time
import warnings   
warnings.filterwarnings("ignore")

mapping = {
    "mappings": {
        "properties": {
            "item_name": {
                "type": "keyword"
            },
            "price": {
                "type": "float"
            }
        }
    }
}

index_name = "students"
# Password for the 'elastic' user generated by Elasticsearch
ELASTIC_PASSWORD = "xxxxx"

query = {"query": {"bool": {"must": {"term": {"item_name": "apple"}}}}}


def connection():
    url = "https://localhost:9200"        
    es = Elasticsearch(url,
                       ca_certs="xxx",
                       basic_auth=("elastic", ELASTIC_PASSWORD))
    return es


def create_index():
    es = connection()
    index_name = "students"
    print("hello")
    try:
        index_exists = es.indices.exists(index=index_name)
        if not index_exists:
            es.indices.create(index=index_name, body=mapping)
            print("Index created successfully!")

    except Exception as err:
        print("Elasticsearch error:", err)


def home(request: Request):
    return True



routes = [Route("/", endpoint=home, methods=[])]          

          
app = Starlette(
    routes=routes
)


@app.on_event("startup")
def on_startup():    
    create_index()

while running this i am getting 500 internal server error

My questions are:

  1. how to create the route path for elastic search
  2. if it possible to create then in which port i can see the output (default port of elasticsearch or starlette)

kindly share some examples

1 Answers

Yes we can access the elastic db with the normal python commands

Related