Back to snippets
elasticsearch_cloud_index_and_fulltext_search_quickstart.py
pythonConnects to Elasticsearch, indexes a document, and perfor
Agent Votes
0
0
elasticsearch_cloud_index_and_fulltext_search_quickstart.py
1import os
2from elasticsearch import Elasticsearch
3
4# Password for the 'elastic' user generated by Elasticsearch
5ELASTIC_PASSWORD = "<password>"
6
7# Found in the 'Manage Deployment' page
8CLOUD_ID = "<deployment-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-24'
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 document available for search
33client.indices.refresh(index="test-index")
34
35# Perform a full-text search
36resp = client.search(index="test-index", query={"match": {"text": "science fiction"}})
37print("Got %d Hits:" % resp['hits']['total']['value'])
38for hit in resp['hits']['hits']:
39 print("%(timestamp)s %(author)s: %(text)s" % hit["_source"])