Bird
0
0

You want to find documents where the category is 'books' and the price is less than 20, but exclude those that are out of stock. Which bool query correctly implements this?

hard🚀 Application Q15 of 15
Elasticsearch - Basic Search Queries
You want to find documents where the category is 'books' and the price is less than 20, but exclude those that are out of stock. Which bool query correctly implements this?
A{ "bool": { "should": [ { "term": { "category": "books" } }, { "range": { "price": { "lt": 20 } } } ], "must_not": [ { "term": { "stock": "out" } } ] } }
B{ "bool": { "filter": [ { "term": { "category": "books" } }, { "range": { "price": { "lt": 20 } } } ], "must_not": { "term": { "stock": "out" } } } }
C{ "bool": { "must": [ { "term": { "category": "books" } }, { "range": { "price": { "lt": 20 } } } ], "must_not": [ { "term": { "stock": "out" } } ] } }
D{ "bool": { "must": { "term": { "category": "books" } }, "filter": { "range": { "price": { "lt": 20 } } }, "must_not": [ { "term": { "stock": "out" } } ] } }
Step-by-Step Solution
Solution:
  1. Step 1: Identify required conditions

    Documents must have category: books and price < 20. Both are required, so they go in must as an array.
  2. Step 2: Exclude out of stock documents

    Documents with stock: out must be excluded, so use must_not with an array of term queries.
  3. Step 3: Check each option

    { "bool": { "must": [ { "term": { "category": "books" } }, { "range": { "price": { "lt": 20 } } } ], "must_not": [ { "term": { "stock": "out" } } ] } } correctly uses must array for required conditions and must_not array for exclusion. { "bool": { "filter": [ { "term": { "category": "books" } }, { "range": { "price": { "lt": 20 } } } ], "must_not": { "term": { "stock": "out" } } } } uses filter which is okay but must_not is an object, not array. { "bool": { "should": [ { "term": { "category": "books" } }, { "range": { "price": { "lt": 20 } } } ], "must_not": [ { "term": { "stock": "out" } } ] } } uses should which makes conditions optional, wrong here. { "bool": { "must": { "term": { "category": "books" } }, "filter": { "range": { "price": { "lt": 20 } } }, "must_not": [ { "term": { "stock": "out" } } ] } } uses must as object and filter as object, mixing styles incorrectly.
  4. Final Answer:

    { "bool": { "must": [ { "term": { "category": "books" } }, { "range": { "price": { "lt": 20 } } } ], "must_not": [ { "term": { "stock": "out" } } ] } } -> Option C
  5. Quick Check:

    Must array + must_not array for exclusion [OK]
Quick Trick: Use must array for required, must_not array to exclude [OK]
Common Mistakes:
MISTAKES
  • Using should instead of must for required filters
  • Using object instead of array for must or must_not
  • Mixing filter and must incorrectly

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Elasticsearch Quizzes