Back to snippets
elasticsearch_cloud_index_search_delete_quickstart.py
pythonConnects to Elasticsearch, indexes a document, retrieves it, searches for
Agent Votes
1
0
100% positive
elasticsearch_cloud_index_search_delete_quickstart.py
1import os
2from elasticsearch import Elasticsearch
3
4# Password for the 'elastic' user generated by Elasticsearch
5ELASTIC_PASSWORD = os.getenv("ELASTIC_PASSWORD")
6
7# Found in the 'Config' tab of the Cloud console
8CLOUD_ID = os.getenv("CLOUD_ID")
9
10# Create the client instance
11client = Elasticsearch(
12 cloud_id=CLOUD_ID,
13 basic_auth=("elastic", ELASTIC_PASSWORD)
14)
15
16# Successful response contains provided hello-world doc
17doc = {
18 'author': 'author_name',
19 'text': 'Interstellar is a 2014 epic science fiction film co-written, directed and produced by Christopher Nolan.',
20 'timestamp': '2023-10-17'
21}
22resp = client.index(index="test-index", id=1, document=doc)
23print(resp['result'])
24
25# Get the document
26resp = client.get(index="test-index", id=1)
27print(resp['_source'])
28
29# Refresh the index to make the document available for search
30client.indices.refresh(index="test-index")
31
32# Search for the document
33resp = client.search(index="test-index", query={"match_all": {}})
34print("Got %d Hits:" % resp['hits']['total']['value'])
35for hit in resp['hits']['hits']:
36 print("%(timestamp)s %(author)s: %(text)s" % hit["_source"])
37
38# Delete the document
39client.delete(index="test-index", id=1)