66 lines
2.2 KiB
Python
66 lines
2.2 KiB
Python
from elasticsearch import Elasticsearch
|
|
|
|
# Create a connection to Elasticsearch
|
|
es = Elasticsearch()
|
|
|
|
# Define an index mapping for customers and orders
|
|
mapping = {
|
|
"mappings": {
|
|
"properties": {
|
|
"customer_name": {"type": "keyword"}
|
|
}
|
|
}
|
|
}
|
|
|
|
order_mapping = {
|
|
"mappings": {
|
|
"properties": {
|
|
"order_id": {"type": "integer"},
|
|
"product_name": {"type": "keyword"},
|
|
"quantity": {"type": "integer"},
|
|
"price": {"type": "float"},
|
|
"customer_id": {"type": "join", "relations": {"customer": "order"}}
|
|
}
|
|
}
|
|
}
|
|
|
|
# Create the customers and orders indices with the mappings
|
|
es.indices.create(index="customers", body=mapping)
|
|
es.indices.create(index="orders", body=order_mapping)
|
|
|
|
# Insert some documents
|
|
es.index(index="customers", body={"customer_name": "Alice"})
|
|
es.index(index="customers", body={"customer_name": "Bob"})
|
|
es.index(index="customers", body={"customer_name": "Charlie"})
|
|
|
|
es.index(index="orders", body={"order_id": 1, "product_name": "Apple", "quantity": 2, "price": 1.00, "customer_id": {"name": "Alice", "parent": "customer"}})
|
|
es.index(index="orders", body={"order_id": 2, "product_name": "Banana", "quantity": 3, "price": 0.50, "customer_id": {"name": "Bob", "parent": "customer"}})
|
|
es.index(index="orders", body={"order_id": 3, "product_name": "Cherry", "quantity": 1, "price": 2.00, "customer_id": {"name": "Charlie", "parent": "customer"}})
|
|
es.index(index="orders", body={"order_id": 4, "product_name": "Banana", "quantity": 1, "price": 0.50, "customer_id": {"name": "Alice", "parent": "customer"}})
|
|
es.index(index="orders", body={"order_id": 5, "product_name": "Durian", "quantity": 2, "price": 3.00, "customer_id": {"name": "Charlie", "parent": "customer"}})
|
|
|
|
# Search for documents
|
|
query = {
|
|
"query": {
|
|
"has_child": {
|
|
"type": "order",
|
|
"query": {
|
|
"match": {
|
|
"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'}
|
|
{'customer_name': 'Bob'}
|
|
''' |