AI Hints
Home›Elasticsearch Tutorial›Searching and Errors in Python
Elasticsearch · Lesson 93 of 120

Errors and Retries

When things go wrong.

⏱ 2 min read▶ Video at 1:27:17🎓 Free
Watch this lesson in the Elasticsearch courseWatch on YouTube ↗Full Elasticsearch course

Real apps hit problems. A missing index, a bad query, or a cluster that's busy for a moment. The client raises clear exceptions, so your app can handle each one.

  • Missing index
  • Bad query
  • Busy cluster

Catching errors

Not found error means the document or index doesn't exist. Bad request error means the query was wrong, and the message says why. Run it. Both errors are caught, with useful messages.

errors.pypython
from elasticsearch import Elasticsearch

es = Elasticsearch("http://localhost:9200")
from elasticsearch import NotFoundError, BadRequestError

try:
    es.get(index="products", id=999)
except NotFoundError:
    print("No product 999")

try:
    es.search(index="products", query={"match": {"price": "cheap"}})
except BadRequestError as e:
    print("Bad query:", e.body["error"]["root_cause"][0]["type"])
Output
No product 999
Bad query: query_shard_exception
Also uses _load
catalog

Retries and timeouts

The client can retry for you. Max retries sets how many tries, and retry on timeout retries slow requests too. Request timeout sets how long to wait. Run it. The client is ready, with safe settings.

client.pypython
from elasticsearch import Elasticsearch

es = Elasticsearch(
    "http://localhost:9200",
    max_retries=3,
    retry_on_timeout=True,
    request_timeout=10,
)
print(es.ping())
Output
True

Summary

Catch not found and bad request errors, and let the client retry with sensible timeouts. Next, reading every document with scan.

Key takeaways
  • NotFoundError
  • BadRequestError
  • max_retries
Next up: Scanning Every Document — read them all