pip install elasticsearch★The official client. Add extras:elasticsearch[async]for the async client. Python 3.10+.from elasticsearch import Elasticsearch es = Elasticsearch("https://localhost:9200", api_key="...")★API key auth is preferred. Alsobasic_auth=("user","pass"), orcloud_id=for Elastic Cloud.es = Elasticsearch("https://localhost:9200", api_key="...", ca_certs="http_ca.crt")TLS on by default for local clusters — point at the CA cert (orverify_certs=Falsefor dev only).es.info() · es.ping()★Sanity check the connection & cluster version.
es.index(index="books", id=1, document={"title":"Dune", "year":1965})★Create/replace a doc. Pass the JSON asdocument=. Omitidto auto-generate one.es.get(index="books", id=1)["_source"]★Fetch by id; the doc body is under_source.es.exists(index=, id=)for a boolean.es.update(index="books", id=1, doc={"year":1966})★Partial update viadoc=(or a script).es.delete(index=, id=)to remove.es.indices.refresh(index="books")noteIndexing is near-real-time (~1s).refresh=Trueon the write, or refresh the index, to make a doc searchable immediately (tests/demos).
from elasticsearch import helpers actions = [{"_index":"books", "_id":d["id"], "_source":d} for d in docs] helpers.bulk(es, actions)★The right way to load many docs — one request per batch, not one per doc. Each action names_index/_id/_source.for ok, item in helpers.streaming_bulk(es, gen(), chunk_size=1000): if not ok: log(item)★streaming_bulkyields per-doc results from a generator — constant memory for huge loads.parallel_bulkfor threads.actions = [{"_op_type":"update", "_id":1, "doc":{...}}, ...]_op_typecan beindex/create/update/deleteper action.# bulk returns (success_count, errors) — check errors!gotchaA partial-failure bulk still "succeeds" at the HTTP level. Inspect the errors list (or passraise_on_error=True).