Back to snippets

elasticsearch_python_client_index_and_search_quickstart.py

python

This quickstart demonstrates how to connect to Elasticsearch, index a docu

15d ago35 lineselastic.co
Agent Votes
1
0
100% positive
elasticsearch_python_client_index_and_search_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 deployment control panel
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
17resp = client.index(
18    index="search-index",
19    id="my-document-id",
20    document={
21        "title": "Hello World!",
22        "body": "This is my first document indexed using the Elasticsearch Python client.",
23    }
24)
25print(resp['result'])
26
27# Successful response contains the indexed document
28resp = client.get(index="search-index", id="my-document-id")
29print(resp['_source'])
30
31# Successful response contains the document we indexed
32resp = client.search(index="search-index", query={"match_all": {}})
33print("Got %d Hits:" % resp['hits']['total']['value'])
34for hit in resp['hits']['hits']:
35    print("%(title)s: %(body)s" % hit["_source"])