52 lines
1.8 KiB
Python
52 lines
1.8 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"},
|
|
"orders": {
|
|
"type": "nested",
|
|
"properties": {
|
|
"order_id": {"type": "integer"},
|
|
"product_name": {"type": "keyword"},
|
|
"quantity": {"type": "integer"},
|
|
"price": {"type": "float"}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
# Create an index with the mapping
|
|
es.indices.create(index="customers", body=mapping)
|
|
|
|
# Insert some documents
|
|
es.index(index="customers", body={"customer_name": "Alice", "orders": [
|
|
{"order_id": 1, "product_name": "Apple", "quantity": 2, "price": 1.00},
|
|
{"order_id": 4, "product_name": "Banana", "quantity": 1, "price": 0.50}
|
|
]})
|
|
es.index(index="customers", body={"customer_name": "Bob", "orders": [
|
|
{"order_id": 2, "product_name": "Banana", "quantity": 3, "price": 0.50}
|
|
]})
|
|
es.index(index="customers", body={"customer_name": "Charlie", "orders": [
|
|
{"order_id": 3, "product_name": "Cherry", "quantity": 1, "price": 2.00},
|
|
{"order_id": 5, "product_name": "Durian", "quantity": 2, "price": 3.00}
|
|
]})
|
|
|
|
# Search for documents
|
|
query = {"query": {"nested": {"path": "orders", "query": {"match": {"orders.product_name": "Banana"}}}}}
|
|
result = es.search(index="customers", body=query)
|
|
|
|
# Print the search results
|
|
for hit in result['hits']['hits']:
|
|
print(hit['_source'])
|
|
|
|
# OUTPUT
|
|
'''
|
|
{'customer_name': 'Alice', 'orders': [{'order_id': 4, 'product_name': 'Banana', 'quantity': 1, 'price': 0.5}]}
|
|
{'customer_name': 'Bob', 'orders': [{'order_id': 2, 'product_name': 'Banana', 'quantity': 3, 'price': 0.5}]}
|
|
''' |