Skip to content
Tutorials Center
My learning

Topics

Lesson 41 of 43 ยท Practice and Review

Practice Exercises with Solutions

Practice Elasticsearch with mapping, query and aggregation exercises written as JSON. Each has a solution and a runnable stand-in check you can edit.

Reading about mappings and queries is one thing; writing them from a blank page is another. This lesson gives you six exercises: two on mappings, two on queries and two on aggregations. Each one states a task, shows a solution and explains why it is right. Try to write your own answer before you open the solution.

Real Elasticsearch is not running on this site, so the requests are read-only JSON that you would send in Kibana Dev Tools or with curl. To make practice more than reading, three exercises have a stand-in check you can run and edit: a small script that evaluates your JSON the way Elasticsearch would for this simple case. The stand-ins support only the features used here. They are teaching aids, not the real engine.

How to use these exercises

Read the task Write your JSON first.
Run the check Edit the stand-in and watch it pass or fail.
Compare Read the solution and the why.

Several correct answers often exist.

1 / 2

Exercise 1: a mapping for a shop

Task. Design the mapping for a shop-products index. Requirements: title is full-text searchable and can also be sorted; sku is matched exactly; price supports range queries and sums; in_stock is true or false; published is a date; tags are exact values used for facets.

Solution (read-only request):

JSON
PUT /shop-products
{
  "mappings": {
    "properties": {
      "title":     { "type": "text", "fields": { "raw": { "type": "keyword" } } },
      "sku":       { "type": "keyword" },
      "price":     { "type": "scaled_float", "scaling_factor": 100 },
      "in_stock":  { "type": "boolean" },
      "published": { "type": "date" },
      "tags":      { "type": "keyword" }
    }
  }
}

Why it works: text is analyzed for full-text search, and the multi-field title.raw is a keyword for sorting (Mappings and Field Types). scaled_float stores money as an integer count of cents, which avoids float rounding issues. A keyword array needs no special type: any field can hold several values.

The stand-in below holds the mapping as a JavaScript object and checks each requirement. Break the mapping (for example change sku to text) and run it again.

JS Check a mapping against requirements

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Exercise 2: avoid a mapping explosion

Task. Documents contain a free-form attributes object with thousands of different keys across the index. What setting stops the mapping from growing without limit, while keeping the data in _source?

Solution:

JSON
PUT /events
{
  "mappings": {
    "properties": {
      "attributes": { "type": "object", "dynamic": false }
    }
  }
}

With dynamic: false, unknown fields inside attributes are kept in _source but not indexed and not added to the mapping. The alternative "type": "flattened" indexes the whole object as one field of keyword values, so you can still search it. dynamic: strict would instead reject documents with unknown fields (Dynamic Mapping and Index Templates).

Exercise 3: a bool query

Task. From a product index, find products whose name contains "running", that are in stock, cost at most 100, and are not from the brand "Terra". Only the text match should affect the score.

Solution:

JSON
GET /products/_search
{
  "query": {
    "bool": {
      "must":     [ { "match": { "name": "running" } } ],
      "filter":   [ { "term": { "in_stock": true } },
                    { "range": { "price": { "lte": 100 } } } ],
      "must_not": [ { "term": { "brand": "Terra" } } ]
    }
  }
}

Why: must scores, while filter and must_not only include or exclude and are cacheable (Bool Queries and Compound Logic). The stand-in below holds five products and a tiny evaluator for match, term, range and bool. Change the query and watch which ids come back.

JS Evaluate a bool query on five products

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Only product 1 passes: product 2 costs 120, product 4 is from Terra, and products 3 and 5 do not contain "running" (3 is also out of stock). The stand-in ignores scoring (it has none) and should clauses. Real bool queries do both.

Exercise 4: a phrase with a little slack

Task. Match documents where title contains the words "quick fox" next to each other, but allow one extra word between them ("quick brown fox" should match).

Solution:

JSON
GET /articles/_search
{
  "query": {
    "match_phrase": { "title": { "query": "quick fox", "slop": 1 } }
  }
}

slop is how many position moves are allowed to line the words up. slop: 0 (the default) requires them to be adjacent (Full-Text Queries).

Exercise 5: top countries and their average order

Task. From an orders index with fields country (keyword) and amount (number), return the two countries with the most orders and the average amount per country. Return no hits, only the aggregation.

Solution:

JSON
GET /orders/_search
{
  "size": 0,
  "aggs": {
    "by_country": {
      "terms": { "field": "country", "size": 2 },
      "aggs": { "avg_amount": { "avg": { "field": "amount" } } }
    }
  }
}

size: 0 skips the hits. terms makes one bucket per country, ordered by doc_count by default, and the nested avg runs inside each bucket (Aggregations: Metrics and Buckets). The stand-in groups six sales and builds the same bucket shape. The real response would also include fields such as doc_count_error_upper_bound.

JS Group, count and average like a terms aggregation

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The US has three orders averaging 60, Germany two averaging 50, and France is cut by size: 2.

Exercise 6: weekly revenue

Task. Using the same index with a date field ordered_at, return the total amount per week.

Solution:

JSON
GET /orders/_search
{
  "size": 0,
  "aggs": {
    "per_week": {
      "date_histogram": { "field": "ordered_at", "calendar_interval": "week" },
      "aggs": { "revenue": { "sum": { "field": "amount" } } }
    }
  }
}

Use calendar_interval for calendar units such as week or month (which vary in length) and fixed_interval for exact durations like 30d.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which clause in a bool query does NOT contribute to the score?

    filter clauses only include or exclude documents and can be cached. must and should add to the score.
  2. 2. You need to sort by a text field. What is the usual approach?

    Text fields are analyzed into tokens and have no doc values by default. A keyword sub-field gives one sortable value per document.
  3. 3. What does "size": 0 do in a search request with aggregations?

    size controls the number of hits returned. Aggregations are computed over all matching documents regardless.
  4. 4. Which interval type fits "per month"?

    Months differ in length, so use the calendar-aware interval. Fixed intervals are exact multiples of a unit like days.

Summary

  • Write the mapping first: pick text for searching, keyword for exact values, sorting and facets, and multi-fields when you need both.
  • Put scoring conditions in must and yes/no conditions in filter or must_not.
  • Use size: 0 when you only want aggregations, and nest sub-aggregations for per-bucket metrics.
  • Stand-ins help you practice the logic, but only a real cluster confirms details such as analysis and scoring.

Next lesson: Elasticsearch Interview Questions.