0
0
Elasticsearchquery~30 mins

Search-as-you-type field in Elasticsearch - Mini Project: Build & Apply

Choose your learning style9 modes available
Search-as-you-type field
📖 Scenario: You are building a search feature for a website that helps users find products quickly as they type. To make the search fast and helpful, you will create a special field in Elasticsearch called a search-as-you-type field. This field lets Elasticsearch find matches even if the user types only part of a word.
🎯 Goal: Create an Elasticsearch index with a search_as_you_type field called product_name. Then add some sample products. Finally, write a query that finds products as the user types part of the name.
📋 What You'll Learn
Create an index called products with a product_name field of type search_as_you_type
Add three products with exact names: Apple iPhone, Apple Watch, and Samsung Galaxy
Write a search query that uses multi_match with type set to bool_prefix to find products by partial input
Print the names of matching products from the search results
💡 Why This Matters
🌍 Real World
Search-as-you-type fields are used in online stores, libraries, and apps to help users find items quickly by typing only part of the name.
💼 Career
Knowing how to set up and query search-as-you-type fields is useful for backend developers, search engineers, and anyone working with Elasticsearch to build fast and user-friendly search features.
Progress0 / 4 steps
1
Create the Elasticsearch index with a search-as-you-type field
Create an index called products with a mapping that defines a field named product_name of type search_as_you_type. Use the Elasticsearch PUT request with the mapping inside the mappings key.
Elasticsearch
Need a hint?

Use the PUT method to create the index. Inside mappings, define properties with product_name as search_as_you_type.

2
Add sample products to the index
Add three documents to the products index with the exact product_name values: Apple iPhone, Apple Watch, and Samsung Galaxy. Use the POST method to add each document with an id of your choice.
Elasticsearch
Need a hint?

Use POST /products/_doc/<id> to add each product. The product_name field must match exactly.

3
Write a search query using multi_match with bool_prefix
Write a search query using POST /products/_search that uses multi_match with type set to bool_prefix. Search the product_name field for the partial input Apple. This will find products starting with 'Apple'.
Elasticsearch
Need a hint?

Use multi_match with type set to bool_prefix. Include product_name and its _2gram and _3gram subfields in fields.

4
Print the names of matching products from the search results
Print the product_name values from the search results of the previous query. Show only the names of the products that matched the partial input Apple.
Elasticsearch
Need a hint?

Extract the product_name from each hit in the search results and print it. The output should list the matching product names line by line.