Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
974 B
2
Indexable
Never
from elasticsearch import Elasticsearch

# Set up connection to Elasticsearch instance
es = Elasticsearch([{'host': 'localhost', 'port': 9200}])

# Create an index (database)
index_name = "my_index"
if not es.indices.exists(index=index_name):
    es.indices.create(index=index_name)

# Sample data
sample_data = [
    {"title": "Document 1", "content": "This is the content of document 1."},
    {"title": "Document 2", "content": "This is the content of document 2."},
    {"title": "Document 3", "content": "This is the content of document 3."}
]

# Index documents
for id, doc in enumerate(sample_data):
    es.index(index=index_name, id=id+1, body=doc)

# Search for documents
search_query = {
    "query": {
        "match": {
            "content": "content"
        }
    }
}
search_results = es.search(index=index_name, body=search_query)

# Print search results
for hit in search_results['hits']['hits']:
    print(hit['_source'])