41 lines
1.6 KiB
Python
41 lines
1.6 KiB
Python
from elasticsearch import Elasticsearch
|
|
|
|
# Create a connection to Elasticsearch
|
|
es = Elasticsearch("http://localhost:9200")
|
|
|
|
# Define an index mapping
|
|
mapping = {
|
|
"mappings": {
|
|
"properties": {
|
|
"customer_name": {"type": "keyword"},
|
|
"order_id": {"type": "integer"},
|
|
"product_name": {"type": "keyword"},
|
|
"quantity": {"type": "integer"},
|
|
"price": {"type": "float"}
|
|
}
|
|
}
|
|
}
|
|
|
|
# Create an index with the mapping
|
|
es.indices.create(index="orders", body=mapping)
|
|
|
|
# Insert some documents
|
|
es.index(index="orders", body={"customer_name": "Alice", "order_id": 1, "product_name": "Apple", "quantity": 2, "price": 1.00})
|
|
es.index(index="orders", body={"customer_name": "Bob", "order_id": 2, "product_name": "Banana", "quantity": 3, "price": 0.50})
|
|
es.index(index="orders", body={"customer_name": "Charlie", "order_id": 3, "product_name": "Cherry", "quantity": 1, "price": 2.00})
|
|
es.index(index="orders", body={"customer_name": "Alice", "order_id": 4, "product_name": "Banana", "quantity": 1, "price": 0.50})
|
|
es.index(index="orders", body={"customer_name": "Charlie", "order_id": 5, "product_name": "Durian", "quantity": 2, "price": 3.00})
|
|
|
|
# Search for documents
|
|
query = {"query": {"match": {"customer_name": "Alice"}}}
|
|
result = es.search(index="orders", body=query)
|
|
|
|
# Print the search results
|
|
for hit in result['hits']['hits']:
|
|
print(hit['_source'])
|
|
|
|
# OUTPUT
|
|
'''
|
|
{'customer_name': 'Alice', 'order_id': 1, 'product_name': 'Apple', 'quantity': 2, 'price': 1.0}
|
|
{'customer_name': 'Alice', 'order_id': 4, 'product_name': 'Banana', 'quantity': 1, 'price': 0.5}
|
|
''' |