AI Hints
Home›Elasticsearch Tutorial›Excluding and Context
Elasticsearch · Lesson 39 of 120

Practice: A Real Shop Query

Put it all together.

⏱ 2 min read▶ Video at 35:43🎓 Free
Watch this lesson in the Elasticsearch courseWatch on YouTube ↗Full Elasticsearch course

Let's build the query behind a real Trailhead search page. A shopper types waterproof, picks the Footwear and Jackets categories, sets a maximum price of two hundred, and ticks in stock only.

  • Typed: waterproof
  • Two categories
  • Under $200
  • In stock

The full query

Must holds the typed words, across name and description. Filter holds the categories, the price limit and in stock. Should gives a small bonus to well reviewed products. Run it. A short, ranked list of waterproof boots and jackets.

Dev Tools Consoletext
GET products/_search?filter_path=hits.total.value,hits.hits._source
{
  "query": { "bool": {
    "must": { "multi_match": { "query": "waterproof",
              "fields": ["name^2", "description"] } },
    "filter": [
      { "terms": { "category.keyword": ["Footwear", "Jackets"] } },
      { "range": { "price": { "lte": 200 } } },
      { "term": { "in_stock": true } } ],
    "should": { "range": { "reviews": { "gte": 300 } } }
  } },
  "_source": ["name", "price"]
}
Output
{
  "hits": {
    "total": {"value": 2},
    "hits": [
      {
        "_source": {
          "name": "Waterproof Hiking Boots",
          "price": 118.99
        }
      },
      {
        "_source": {
          "name": "Breeze Rain Jacket",
          "price": 110.99
        }
      }
    ]
  }
}
Also uses _load
products

The pattern

This is the pattern behind most search pages. Text goes in must, so it's ranked. Every checkbox and slider goes in filter. Business preferences go in should. And anything to hide goes in must not.

keyvalue
Typed textmust
Checkboxes, slidersfilter
Preferencesshould
Hidemust_not

Summary

Text in must, checkboxes in filter, bonuses in should, and exclusions in must not. That's a real search page. Next, mappings, and how fields get their types.

Key takeaways
  • must = text
  • filter = facets
  • should = bonus
Next up: Dynamic Mapping — how fields get types