Connecting to the Elastic Cloud cluster with Python
Now let's look at how to connect to Elastic Cloud using the Elasticsearch Python library.
Getting ready
The code for this recipe is in the 11/01/elasticcloud_starwars.py
script. This script will scrape Star Wars character data from the swapi.co API/website and put it into the Elastic Cloud.
How to do it
We proceed with the recipe as follows:
- Execute the file as a Python script:
$ python elasticcloud_starwars.py
- This will loop through up to 20 characters and drop them into the
sw
index with a document type ofpeople
. The code is straightforward (replace the URL with yours):
from elasticsearch import Elasticsearch import requests import json if __name__ == '__main__': es = Elasticsearch( [ "https://elastic:tduhdExunhEWPjSuH73O6yLS@d7c72d3327076cc4daf5528103c46a27.us-west-2.aws.found.io:9243" ]) i = 1 while i<20: r = requests.get('http://swapi.co/api/people/' + str(i)) if r.status_code is not 200: ...