Index, search, get, and delete documents from Elasticsearch using the Python client library.
Elasticsearch Python Client
pip install elasticsearch
from elasticsearch import Elasticsearch
es = Elasticsearch("http://localhost:9200")
# Index a document
es.index(index="posts", id=1, body={
"title": "Docker Guide",
"author": "alice",
"tags": ["docker", "devops"]
})
# Search
result = es.search(index="posts", body={
"query": {
"multi_match": {
"query": "docker containers",
"fields": ["title", "body"]
}
}
})
for hit in result["hits"]["hits"]:
print(hit["_score"], hit["_source"]["title"])
# Get
doc = es.get(index="posts", id=1)
# Delete
es.delete(index="posts", id=1)