AI Hints
Home›Elasticsearch Tutorial›Elasticsearch from Python
Elasticsearch · Lesson 89 of 120

Indexing from Python

Create, update, delete.

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

Trailhead's product team edits products in their own app. Each change has to reach Elasticsearch. Let's create an index with a mapping, then add, update and delete documents from Python.

  • Create the index
  • Add
  • Update
  • Delete

An index with a mapping

Indices create takes the mappings as a dictionary. Then we index two products. Refresh makes them searchable now. Run it. Two products in a fresh, mapped index.

create.pypython
from elasticsearch import Elasticsearch

es = Elasticsearch("http://localhost:9200")

es.indices.create(index="products", mappings={"properties": {
    "name": {"type": "text"},
    "price": {"type": "double"}}})

es.index(index="products", id=1, document={"name": "Trail Mug", "price": 12.5})
es.index(index="products", id=2, document={"name": "Camp Chair", "price": 45})
es.indices.refresh(index="products")
print(es.count(index="products")["count"], "products")
Output
2 products

Update and delete

Update changes only the fields you pass. Delete removes a document by ID. Run it. The mug has a new price, and the chair is gone.

change.pypython
from elasticsearch import Elasticsearch

es = Elasticsearch("http://localhost:9200")

es.index(index="products", id=1, document={"name": "Trail Mug", "price": 12.5})
es.index(index="products", id=2, document={"name": "Camp Chair", "price": 45})

es.update(index="products", id=1, doc={"price": 9.99})
es.delete(index="products", id=2)

print(es.get(index="products", id=1)["_source"])
print(es.exists(index="products", id=2))
Output
{'name': 'Trail Mug', 'price': 9.99}
False

Summary

Create indices with mappings, then index, update and delete documents, all from Python. Next, loading many documents fast with bulk helpers.

Key takeaways
  • indices.create
  • index / update
  • delete
Next up: Bulk Helpers — thousands at once