Bird
Raised Fist0

How would you write a painless script for a runtime field age_category that returns "senior" if age ≥ 65, "adult" if age ≥ 18 but less than 65, and "child" otherwise?

hard🚀 Application Q9 of Q15
Elasticsearch - Advanced Patterns
How would you write a painless script for a runtime field age_category that returns "senior" if age ≥ 65, "adult" if age ≥ 18 but less than 65, and "child" otherwise?
A"source": "if (doc['age'].value >= 18) { emit('adult') } else if (doc['age'].value >= 65) { emit('senior') } else { emit('child') }"
B"source": "if (doc['age'].value > 65) { emit('senior') } else if (doc['age'].value > 18) { emit('adult') } else { emit('child') }"
C"source": "if (doc['age'].value >= 65) { emit('senior') } else if (doc['age'].value >= 18) { emit('adult') } else { emit('child') }"
D"source": "emit(doc['age'].value >= 65 ? 'senior' : doc['age'].value >= 18 ? 'adult' : 'child')"
Step-by-Step Solution
Solution:
  1. Step 1: Understand the conditions

    Return 'senior' if age >= 65, 'adult' if age >= 18 and less than 65, else 'child'.
  2. Step 2: Evaluate options

    "source": "if (doc['age'].value >= 65) { emit('senior') } else if (doc['age'].value >= 18) { emit('adult') } else { emit('child') }" correctly checks >= 65 first, then >= 18, then else.
    "source": "if (doc['age'].value > 65) { emit('senior') } else if (doc['age'].value > 18) { emit('adult') } else { emit('child') }" uses > instead of >=, which excludes exact 65 and 18.
    "source": "if (doc['age'].value >= 18) { emit('adult') } else if (doc['age'].value >= 65) { emit('senior') } else { emit('child') }" checks >= 18 before >= 65, which causes incorrect categorization.
    "source": "emit(doc['age'].value >= 65 ? 'senior' : doc['age'].value >= 18 ? 'adult' : 'child')" uses ternary operators correctly but is less readable; however, it is logically correct but not the best for clarity.
  3. Final Answer:

    "source": "if (doc['age'].value >= 65) { emit('senior') } else if (doc['age'].value >= 18) { emit('adult') } else { emit('child') }" is the clearest and correct implementation.
  4. Quick Check:

    Check order and comparison operators [OK]
Quick Trick: Check comparison operators and condition order [OK]
Common Mistakes:
MISTAKES
  • Using > instead of >= causing boundary errors
  • Incorrect order of conditions
  • Misplacing else blocks

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Elasticsearch Quizzes