I'm trying to set up a run time field to calculate the total of an e-commerce purchase. But there is something wrong with the way I'm declaring run time field, and it might have something to do with nested objects.
First I set up the index , the mapping and the runtime field like this:
PUT purchase
PUT purchase/_mapping
{
"properties": {
"items": {
"type": "nested",
"properties": {
"product_id": {
"type": "long"
},
"quantity": {
"type": "long"
},
"product": {
"properties": {
"name": {
"type": "keyword"
},
"product_id": {
"type": "long"
},
"price": {
"type": "long"
}
}
}
}
},
"purchase_date": {
"type": "date"
}
},
"runtime": {
"items.total": {
"type": "long",
"script": {
"source": "emit(doc['items.quantity'].value * doc['items.product.price'].value)"
}
}
}
}
Then I post one test record lie this:
POST purchase/_doc
{
"purchase_date": "2023-01-01",
"items": [
{
"quantity": 2,
"product_id": 1,
"product": {
"product_id": 1,
"name": "pencil",
"price": 1
}
},
{
"quantity": 4,
"product_id": 2,
"product": {
"product_id": 2,
"name": "stapler",
"price": 5
}
}
]
}
When I do a GET purchase/_search
, I get a result like this:
{
"purchase_date": "2023-01-01",
"items": [
{
"quantity": 2,
"product_id": 1,
"product": {
"product_id": 1,
"name": "pencil",
"price": 1
}
},
{
"quantity": 4,
"product_id": 2,
"product": {
"product_id": 2,
"name": "stapler",
"price": 5
}
}
]
}
I was expecting a field order_items.total
to be a sibling field to order_items.quantity
. I've tried quite a few things but nothing seems to get the order_items.total
field to appear.
What did I do wrong?