[[examples]]
== Examples

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

* <<ex-index>>
* <<ex-get>>
* <<ex-refresh>>
* <<ex-search>>
* <<ex-update>>
* <<ex-delete>>

[discrete]
[[ex-index]]
=== Indexing a document
  
To index a document, you need to specify three pieces of information: `index`, 
`id`, and a `document`:

[source,py]
----------------------------
from datetime import datetime
from elasticsearch import Elasticsearch
client = Elasticsearch('https://localhost:9200')

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


[discrete]
[[ex-get]]
=== Getting a document 

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

[source,py]
----------------------------
resp = client.get(index="test-index", id=1)
print(resp['_source'])
----------------------------


[discrete]
[[ex-refresh]]
=== Refreshing an index

You can perform the refresh operation on an index:

[source,py]
----------------------------
client.indices.refresh(index="test-index")
----------------------------


[discrete]
[[ex-search]]
=== Searching for a document

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

[source,py]
----------------------------
resp = client.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"])
----------------------------


[discrete]
[[ex-update]]
=== Updating a document

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

[source,py]
----------------------------
from datetime import datetime
from elasticsearch import Elasticsearch

client = Elasticsearch('https://localhost:9200')

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


[discrete]
[[ex-delete]]
=== Deleting a document

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

[source,py]
----------------------------
client.delete(index="test-index", id=1)
----------------------------
