Header Ads

Header ADS

Script_Metric Aggregation


🎯 1. Scripted Metric কি?

👉 Scripted Metric হলো:

তুমি নিজের logic লিখে aggregation করো

👉 মানে:

  1. built-in avg, sum না

  2. তুমি নিজেই calculation define করো


🧠 Simple Analogy

ধরো:

👉 OpenSearch default দেয়:

  1. avg(price)

  2. sum(price)

❌ কিন্তু তুমি চাইছো:

"price > 100 হলে শুধু সেগুলোর sum করবো"

👉 এটা default aggregation দিয়ে করা কঠিন

👉 তাই:
✔️ Scripted Metric use করি


🔥 2. Structure (সবচেয়ে important)

Scripted Metric ৪টা step এ কাজ করে:

1. init_script
2. map_script
3. combine_script
4. reduce_script

🧠 Easy Way to Understand (Story)

ধরো 3টা server (shard) আছে


🔹 1. init_script (start)

👉 শুরুতে empty state বানাও

state.total = 0

🔹 2. map_script (each document)

👉 প্রতিটা document এ run হয়

state.total += doc.price.value

👉 মানে:

  • প্রতিটা doc থেকে price নিয়ে যোগ করো


🔹 3. combine_script (per shard)

👉 প্রতিটা shard এর total return করে

return state.total

🔹 4. reduce_script (final result)

👉 সব shard result combine করে

double sum = 0;
for (s in states) {
  sum += s;
}
return sum;

🎯 Full Example

GET sales_data/_search
{
  "size": 0,
  "aggs": {
    "custom_total": {
      "scripted_metric": {
        "init_script": "state.total = 0",
        "map_script": "state.total += doc.price.value",
        "combine_script": "return state.total",
        "reduce_script": "double sum = 0; for (s in states) { sum += s } return sum"
      }
    }
  }
}

📊 Output

{
  "aggregations": {
    "custom_total": {
      "value": 5000
    }
  }
}

🎯 Real Use Cases

✅ Case 1: Conditional Sum

👉 শুধু price > 100 হলে যোগ করো

if (doc.price.value > 100) {
  state.total += doc.price.value
}


🧠 Mentor Trick (Best Way to Remember)

Normal Aggregation → fixed logic
Scripted Metric → custom logic

💬 Final Simple Example

👉 built-in:

sum(price)

👉 scripted:

sum(price where price > 100)


Powered by Blogger.