Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
ElasticSearch Blueprints
ElasticSearch Blueprints

ElasticSearch Blueprints: A practical project-based guide to generating compelling search solutions using the dynamic and powerful features of Elasticsearch

eBook
₱579.99 ₱2000.99
Paperback
₱2500.99
Subscription
Free Trial

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

ElasticSearch Blueprints

Chapter 2. Building Your Own E-Commerce Solution

In the first chapter, we discussed how to add documents to an Elasticsearch instance as well as how to create the fields and decide on an analyzer. All these are steps to get you started. The next two chapters help you to get accustomed to the process of creating an e-commerce search solution. E-commerce revolutionized ways to shop, and the convenience that such a trading system provides attracted people very much. Amazon, eBay, and Flipkart are all pioneers in this field. Elasticsearch offers wonderful support to build such platforms, where you can display what you have. There are numerous techniques that can push the user experience even higher, which can eventually reflect on the overall performance of such a system. This is what we deal with in this chapter. Take a look at the contents of this chapter:

  • Building the document
  • A query or filter—the right choice
  • A date-range-based filter
  • A prize-range-based filter
  • A category-based...

Data modeling in Elasticsearch

Data is modeled in documents in Elasticsearch. This means a single item irrespective of whether it is an entity like a company, country, or product has to be modeled as a single document. A document can contain any number of fields and values associated with it. This information is modeled around the JSON format that helps us to express the behavior of our data using arrays, objects, or simple values.

Note

Elasticsearch is schemaless, which means that you can index a document to Elasticsearch before you create its index or mapping. Elasticsearch guesses the best type for each field value.

Inherently, JSON supports formats such as string, numbers, object, array, and even Boolean. Elasticsearch adds various other formats on top of it, such as the date, IP and so on. You will find the list of such supported types in the following table. The use of date types to store date values will help us do effective date-specific operations, such as date range and aggregation...

Choosing between a query and a filter

The basic idea of a search is to narrow down on a subset of documents that you have. In the Elasticsearch context, this means that based on various conditions, you might want to select a set of documents from an index or a set of index. A query and filter facilitate this for you.

If you have already gone through the reference guide or some other documentation of Elasticsearch, you might have noticed that the same set of operations might be available for both queries and filters. So, what are the differentiating factors of a query and filter even when the set of operations given by them are almost the same? Let's find out.

In a query, a matched document can be a better match than another matched document. In a filter, all the matched documents are treated equally.

This means that there is a way to score or rank a document matched against a query to another document match. This is done by computing a score value that tells you how good a match a particular...

Searching your documents

To search we use a large set of documents and our interest here lies only in a subset of this document set. This can be based on a set of constraints and conditions. A search does not stop here. You might be interested in getting a snapshot view of your query result. In our case, if the user searches for dell, he/she might be interested in seeing different unique product types and their document count. This is called an aggregation. Through this, we enhance our search experience and make it more explorable. Here, we try to discover various querying options through which we can express our requirement and communicate the same to Elasticsearch.

In our search application, we expose a search box that can be used for a search. We abstract out information about which field is searched or what is the precedence of the fields that we search. Let's see the query types that would be best for this search box.

A match query

A match query is the ideal place to start your query...

Aggregating your results

Next, when I search for Lenovo, I would like to see different product types associated with it. This is more like making a report out of the results, but then, as this makes your data more explorable and easy to understand, it's safe to see this as enhancing search capabilities.

Hence, whenever I search for something, I want to see the following reports on my query results or rather, an aggregate of my results in the following information:

  • Different types of productType
  • The number of products in various predefined price ranges
  • The number of documents per year based on manufacturing dates

For this, we need to build different aggregations to capture these reports.

Note

It's very important to understand that the score of aggregation is the query. This means that the aggregations would only be done on those documents that match the query.

The format in which we should provide aggregations is as follows:

{
    "query" : { ….},
    "aggregations...

Filter your results based on a date range

With a fair idea in mind of when to use your filter and when to opt for a query, let's think of some scenarios and see how Elasticsearch enables filtering at its best. Filtering by a date range, prize, or department often pops up in use cases in an e-commerce view. Look at the left-hand side of the following figure:

Filter your results based on a date range

Checking for new arrivals or selecting an old classic song from a library may need a date-range-based filtering mechanism. Elasticsearch provides inbuilt facilities to do filtering by providing a date range filter. A term filter does the same thing for strings, which can be anything for example, a department or category. A numeric filter filters numerals and can be used for prizes and so on.

This snippet shows how you can implement a date-range-based filtering in Elasticsearch:

{
"query" : 
{ "filtered" :
  { "query" :
    { "text" : { "content" : "any keywords to match" ...

Data modeling in Elasticsearch


Data is modeled in documents in Elasticsearch. This means a single item irrespective of whether it is an entity like a company, country, or product has to be modeled as a single document. A document can contain any number of fields and values associated with it. This information is modeled around the JSON format that helps us to express the behavior of our data using arrays, objects, or simple values.

Note

Elasticsearch is schemaless, which means that you can index a document to Elasticsearch before you create its index or mapping. Elasticsearch guesses the best type for each field value.

Inherently, JSON supports formats such as string, numbers, object, array, and even Boolean. Elasticsearch adds various other formats on top of it, such as the date, IP and so on. You will find the list of such supported types in the following table. The use of date types to store date values will help us do effective date-specific operations, such as date range and aggregation...

Choosing between a query and a filter


The basic idea of a search is to narrow down on a subset of documents that you have. In the Elasticsearch context, this means that based on various conditions, you might want to select a set of documents from an index or a set of index. A query and filter facilitate this for you.

If you have already gone through the reference guide or some other documentation of Elasticsearch, you might have noticed that the same set of operations might be available for both queries and filters. So, what are the differentiating factors of a query and filter even when the set of operations given by them are almost the same? Let's find out.

In a query, a matched document can be a better match than another matched document. In a filter, all the matched documents are treated equally.

This means that there is a way to score or rank a document matched against a query to another document match. This is done by computing a score value that tells you how good a match a particular...

Searching your documents


To search we use a large set of documents and our interest here lies only in a subset of this document set. This can be based on a set of constraints and conditions. A search does not stop here. You might be interested in getting a snapshot view of your query result. In our case, if the user searches for dell, he/she might be interested in seeing different unique product types and their document count. This is called an aggregation. Through this, we enhance our search experience and make it more explorable. Here, we try to discover various querying options through which we can express our requirement and communicate the same to Elasticsearch.

In our search application, we expose a search box that can be used for a search. We abstract out information about which field is searched or what is the precedence of the fields that we search. Let's see the query types that would be best for this search box.

A match query

A match query is the ideal place to start your query....

Aggregating your results


Next, when I search for Lenovo, I would like to see different product types associated with it. This is more like making a report out of the results, but then, as this makes your data more explorable and easy to understand, it's safe to see this as enhancing search capabilities.

Hence, whenever I search for something, I want to see the following reports on my query results or rather, an aggregate of my results in the following information:

  • Different types of productType

  • The number of products in various predefined price ranges

  • The number of documents per year based on manufacturing dates

For this, we need to build different aggregations to capture these reports.

Note

It's very important to understand that the score of aggregation is the query. This means that the aggregations would only be done on those documents that match the query.

The format in which we should provide aggregations is as follows:

{
    "query" : { ….},
    "aggregations" : { 
        "aggregationNameA...

Filter your results based on a date range


With a fair idea in mind of when to use your filter and when to opt for a query, let's think of some scenarios and see how Elasticsearch enables filtering at its best. Filtering by a date range, prize, or department often pops up in use cases in an e-commerce view. Look at the left-hand side of the following figure:

Checking for new arrivals or selecting an old classic song from a library may need a date-range-based filtering mechanism. Elasticsearch provides inbuilt facilities to do filtering by providing a date range filter. A term filter does the same thing for strings, which can be anything for example, a department or category. A numeric filter filters numerals and can be used for prizes and so on.

This snippet shows how you can implement a date-range-based filtering in Elasticsearch:

{
"query" : 
{ "filtered" :
  { "query" :
    { "text" : { "content" : "any keywords to match" }
  },
 "filter" : 
{ "numeric_range" :
 { "date" :
     { "lt" : ...

Implementing a prize range filter


Now, let's move on and see how to implement a prize range filter as seen in some e-commerce websites. Consider the following screenshot of an e-commerce site:

In the preceding screenshot, you can see a price range filter on the left-hand side tab. By clicking on or specifying the price ranges, the products that fall within that range would be displayed. This is nothing but a numeric range filter.

The implementation of a numeric range filter is almost similar to the date range filter in Elasticsearch. The following code snippet shows how to implement a numeric range filter. Here is the sample; assume that you have an age field that is numeric in nature:

{
    "filtered" : {
        "filter" : {
            "range" : {
                "age" : {
                    "gte": 10,
                    "lte": 20
                }
            }
        }
    }
}

After reading the implementation of filters, which is to be followed, you would understand the snippet completely...

Implementing a category filter


Normally, the category fields are of the type string. We need to index this unanalyzed field to match the exact term. In fact, Elasticsearch uses a term filter for the purpose of matching strings:

The following snippet shows you how to use a terms filter:

{
    "filtered" : {
        "filter" : {
            "term" : {
                "category" : "Books"
        
            }
        }
    }
}

Implementation of filters in Elasticsearch


This section sheds some light on the implementation of filters in Elasticsearch. All filters are not the same. We will see how each one differs from another and how we can implement these with Elasticsearch. First, let's see all the three implementation types of filters in Elasticsearch.

We have already showed you the most basic type of usage of a filter in the previous examples. You would have noticed the term constant score or filtered every time we used a filter. These are queries and they wrap the filter inside and apply it against the normal query's result. This is the first type of filter implementation of Elasticsearch.

Note that the filtered/constant score implementation of filters will affect both the results of the query and aggregations; some of the examples are shown as follows:

curl -XPOST 'http://localhost:9200/products/_search?pretty' -d '{
   "aggregations": {
     "department": {
       "terms": {
         "field": "color"
       ...

Searching with multiple conditions


Often, we find ourselves in a position where we need to search with more than one criterion, where each of these criteria could be expressed as an individual query. In this section, let's see how we can make such a combination of search.

One simple way to express multiple search criteria is using a bool query. The bool query lets you use a combination of other queries, where each of the conditions can be put using a Boolean clause. There are three Boolean clauses:

  • must

  • should

  • must_not

The must clause suggests that the constituent query must appear in the matching documents. If there is no must clause in the query, a combination of should clauses can be given. Also, you may set the minimum number of should clauses that should be matched. As the name indicates, must_not means that this clause should not match the document.

Let's see how we can use the bool query in Elasticsearch:

{
    "bool" : {
        "must" : [{
            "term" : { "productType" : ...
Left arrow icon Right arrow icon

Description

If you are a data enthusiast and would like to explore and specialize on search technologies based on Elasticsearch, this is the right book for you. A compelling case-to-case mapping of features and implementation of Elasticsearch to solve many real-world use cases makes this book the right choice to start and specialize on Elasticsearch.

Who is this book for?

If you are a data enthusiast and would like to explore and specialize on search technologies based on Elasticsearch, this is the right book for you. A compelling case-to-case mapping of features and implementation of Elasticsearch to solve many real-world use cases makes this book the right choice to start and specialize on Elasticsearch.

What you will learn

  • Build a simple scalable server for effective searching in Elasticsearch
  • Design a scalable ecommerce search solution to generate accurate search results using various filters such as filters based on date range and price range
  • Improve the relevancy and scoring of your searches
  • Manage realworld, complex data using various techniques, including parentchild search and searching questions based on the criteria of questions and answers
  • Use the excellent data crunching and aggregation capability of Elasticsearch to analyze your data
  • Generate realtime visualizations of your data using compelling visualization techniques, such as time graphs, pie charts, and stacked graphs
  • Enhance the quality of your search and widen the scope of matches using various analyzer techniques, such as lower casing, stemming, and synonym matching

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jul 24, 2015
Length: 192 pages
Edition : 1st
Language : English
ISBN-13 : 9781783984923
Vendor :
Elastic
Category :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Jul 24, 2015
Length: 192 pages
Edition : 1st
Language : English
ISBN-13 : 9781783984923
Vendor :
Elastic
Category :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just ₱260 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just ₱260 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 8,420.97
Elasticsearch Server: Second Edition
₱2806.99
ElasticSearch Blueprints
₱2500.99
ElasticSearch Cookbook - Second Edition
₱3112.99
Total 8,420.97 Stars icon
Banner background image

Table of Contents

9 Chapters
1. Google-like Web Search Chevron down icon Chevron up icon
2. Building Your Own E-Commerce Solution Chevron down icon Chevron up icon
3. Relevancy and Scoring Chevron down icon Chevron up icon
4. Managing Relational Content Chevron down icon Chevron up icon
5. Analytics Using Elasticsearch Chevron down icon Chevron up icon
6. Improving the Search Experience Chevron down icon Chevron up icon
7. Spicing Up a Search Using Geo Chevron down icon Chevron up icon
8. Handling Time-based Data Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
(2 Ratings)
5 star 50%
4 star 0%
3 star 0%
2 star 0%
1 star 50%
Quentin FAYET Sep 22, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I read that book to improve my knowledge about Elasticsearch.After reading "Elasticsearch Server" from the same editor, I was searching for a book with complete examples, from basic stuff to more complicated topics (such as Geolocalized requests).Well, this book did the job perfectly.Going from "basic" stuff, such as "Google style" full-text search, to more complex notions such as geolocalized requests, this book is reviewing every important feature of the amazing Elasticsearch.Other interesting such as data analysis, or even seach experience and search optimizations are exposed in this book.I would say this book is really complete, and I would definitely recommand it.
Amazon Verified review Amazon
Jeremy McLain Dec 16, 2016
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1
This would have been a good book if it had been written in intelligible English. It's riddled with incoherent sentences, grammar mistakes, and misspellings. I don't mean a few dozen mistakes - nearly every paragraph has a major sentence construction or spelling error. It's obvious that English is not the first language of both the author and the editor. I applaud their effort to attempt to write a book in a non-native language, but Packt Publishing should have had it reviewed by a native English speaker before it was published.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.