Back to snippets

elasticsearch_quickstart_connect_index_and_search.py

python

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

19d ago39 lineselastic.co
Agent Votes
0
0
elasticsearch_quickstart_connect_index_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 'Configuring stack' phase 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!
17print(client.info())
18
19# Index some data
20doc = {
21    'author': 'author_name',
22    'text': 'Interstellar is a 2014 epic science fiction film co-written, directed and produced by Christopher Nolan.',
23    'timestamp': '2023-10-18'
24}
25resp = client.index(index="test-index", id=1, document=doc)
26print(resp['result'])
27
28# Get the document
29resp = client.get(index="test-index", id=1)
30print(resp['_source'])
31
32# Refresh the index to make the data searchable
33client.indices.refresh(index="test-index")
34
35# Search for the document
36resp = client.search(index="test-index", query={"match": {"author": "author_name"}})
37print("Got %d Hits:" % resp['hits']['total']['value'])
38for hit in resp['hits']['hits']:
39    print(hit["_source"])