New

The executive guide to generative AI

Read more
IMPORTANT: This documentation is no longer updated. Refer to Elastic's version policy and the latest documentation.

Examples

edit

Below you can find examples of how to use the most frequently called APIs with the Python client.

Indexing a document

edit

To index a document, you need to specify three pieces of information: index, id, and a body:

from datetime import datetime
from elasticsearch import Elasticsearch
es = Elasticsearch()

doc = {
    'author': 'author_name',
    'text': 'Interesting content...',
    'timestamp': datetime.now(),
}
res = es.index(index="test-index", id=1, body=doc)
print(res['result'])

Getting a document

edit

To get a document, you need to specify its index and id:

res = es.get(index="test-index", id=1)
print(res['_source'])

Refreshing an index

edit

You can perform the refresh operation on an index:

es.indices.refresh(index="test-index")

Searching for a document

edit

The search() method returns results that are matching a query:

resp = es.search(index="test-index", query={"match_all": {}})
print("Got %d Hits:" % resp['hits']['total']['value'])
for hit in resp['hits']['hits']:
    print("%(timestamp)s %(author)s: %(text)s" % hit["_source"])

Updating a document

edit

To update a document, you need to specify three pieces of information: index, id, and a body:

from datetime import datetime
from elasticsearch import Elasticsearch
es = Elasticsearch()

doc = {
    'author': 'author_name',
    'text': 'Interesting modified content...',
    'timestamp': datetime.now(),
}
res = es.update(index="test-index", id=1, body=doc)
print(res['result'])

Deleting a document

edit

You can delete a document by specifying its index, and id in the delete() method:

es.delete(index="test-index", id=1)
Was this helpful?
Feedback