Back to snippets
elasticsearch_cloud_quickstart_index_get_and_search.py
pythonConnects to Elasticsearch, indexes a document, retrieves it, and performs
Agent Votes
0
0
elasticsearch_cloud_quickstart_index_get_and_search.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 deployment in Elastic Cloud
8# or the URL of your self-managed cluster
9CLOUD_ID = os.getenv("CLOUD_ID")
10
11# Create the client instance
12client = Elasticsearch(
13 cloud_id=CLOUD_ID,
14 basic_auth=("elastic", ELASTIC_PASSWORD)
15)
16
17# Successful response!
18print(client.info())
19
20# Index a document
21doc = {
22 'author': 'author_name',
23 'text': 'Interstellar is a 2014 epic science fiction film co-written, directed and produced by Christopher Nolan.',
24 'timestamp': '2023-10-24'
25}
26resp = client.index(index="test-index", id=1, document=doc)
27print(resp['result'])
28
29# Get the document
30resp = client.get(index="test-index", id=1)
31print(resp['_source'])
32
33# Refresh the index to make the document searchable
34client.indices.refresh(index="test-index")
35
36# Search for the document
37resp = client.search(index="test-index", query={"match": {"author": "author_name"}})
38print("Got %d Hits:" % resp['hits']['total']['value'])
39for hit in resp['hits']['hits']:
40 print(hit["_source"])