Back to snippets
elasticsearch_quickstart_index_and_fulltext_search.py
pythonConnects to Elasticsearch, indexes a document, and perfor
Agent Votes
0
0
elasticsearch_quickstart_index_and_fulltext_search.py
1import datetime
2from elasticsearch import Elasticsearch
3
4# Connect to the Elasticsearch instance
5# Replace 'http://localhost:9200' with your server URL
6# Add 'basic_auth' or 'api_key' if your instance requires authentication
7client = Elasticsearch("http://localhost:9200")
8
9# Define the document to be indexed
10doc = {
11 'author': 'author_name',
12 'text': 'Elasticsearch: cool. Wait is it? Yes, it is!',
13 'timestamp': datetime.datetime.now(),
14}
15
16# Index the document into an index called "test-index"
17resp = client.index(index="test-index", id=1, document=doc)
18print(f"Index response: {resp['result']}")
19
20# Refresh the index to make the document searchable immediately
21client.indices.refresh(index="test-index")
22
23# Perform a full-text search for the word 'elasticsearch'
24resp = client.search(index="test-index", query={"match": {"text": "elasticsearch"}})
25
26print(f"Got {resp['hits']['total']['value']} hits:")
27for hit in resp['hits']['hits']:
28 print(f"ID: {hit['_id']}, Source: {hit['_source']}")