Tutorial: Supported Query Types in Elasticsearch

Avatar

By squashlabs, Last Updated: October 25, 2023

Tutorial: Supported Query Types in Elasticsearch

Elasticsearch is a useful open-source search and analytics engine that is built on top of Apache Lucene. It provides a distributed, RESTful search and analytics platform capable of handling large amounts of data. One of the key features of Elasticsearch is its versatile query capabilities. In this article, we will explore the various query types supported by Elasticsearch and how they can be used to search and analyze data effectively.

Elasticsearch Query Types

Elasticsearch supports a wide range of query types that cater to different search and analysis requirements. These query types can be broadly categorized into search queries and filter queries.

Related Article: How to Use the aria-label Attribute in HTML

Elasticsearch Search Queries

Search queries in Elasticsearch are used to retrieve documents that match specific search criteria. These queries can be simple or complex, depending on the requirements. Elasticsearch provides several search query types, including:

Elasticsearch Full-Text Search

Full-text search is one of the most commonly used query types in Elasticsearch. It allows you to search for documents based on the presence of specific terms or phrases in the indexed data. Elasticsearch uses an inverted index to efficiently perform full-text searches. Here’s an example of a full-text search query in Elasticsearch:

{
  "query": {
    "match": {
      "content": "elasticsearch"
    }
  }
}

In this example, we are searching for documents that contain the term “elasticsearch” in the “content” field.

Elasticsearch Term Query

The term query in Elasticsearch is used to search for exact matches of terms in the indexed data. Unlike full-text search, the term query does not analyze the search terms and performs an exact match. Here’s an example of a term query in Elasticsearch:

{
  "query": {
    "term": {
      "status": "published"
    }
  }
}

In this example, we are searching for documents that have the term “published” in the “status” field.

Elasticsearch Match Query

The match query is a versatile query type in Elasticsearch that allows you to perform full-text searches, phrase searches, and more. It analyzes the search terms and matches them against the indexed data. Here’s an example of a match query in Elasticsearch:

{
  "query": {
    "match": {
      "title": "Elasticsearch tutorial"
    }
  }
}

In this example, we are searching for documents that have the phrase “Elasticsearch tutorial” in the “title” field.

Elasticsearch Range Query

The range query in Elasticsearch is used to search for documents that fall within a specified range of values. It can be used to search for numeric, date, or string values. Here’s an example of a range query in Elasticsearch:

{
  "query": {
    "range": {
      "price": {
        "gte": 100,
        "lte": 500
      }
    }
  }
}

In this example, we are searching for documents where the “price” field is greater than or equal to 100 and less than or equal to 500.

Elasticsearch Bool Query

The bool query in Elasticsearch allows you to combine multiple queries using boolean operators such as must, should, and must_not. It provides a useful way to express complex search criteria. Here’s an example of a bool query in Elasticsearch:

{
  "query": {
    "bool": {
      "must": [
        { "match": { "title": "Elasticsearch" } },
        { "range": { "price": { "gte": 100 } } }
      ],
      "must_not": [
        { "term": { "status": "out_of_stock" } }
      ]
    }
  }
}

In this example, we are searching for documents where the “title” field contains the term “Elasticsearch” and the “price” field is greater than or equal to 100, excluding documents that have the “status” field set to “out_of_stock”.

Elasticsearch Filter Query

Filter queries in Elasticsearch are used to narrow down the search results based on specific criteria. Unlike search queries, filter queries do not affect the relevance score of the documents. Elasticsearch provides several filter query types, including:

Elasticsearch Filter Query

The filter query in Elasticsearch is used to apply filters to the search results. It allows you to define conditions that the documents must satisfy to be included in the search results. Here’s an example of a filter query in Elasticsearch:

{
  "query": {
    "bool": {
      "filter": [
        { "term": { "category": "electronics" } },
        { "range": { "price": { "gte": 100 } } }
      ]
    }
  }
}

In this example, we are searching for documents that have the “category” field set to “electronics” and the “price” field greater than or equal to 100.

Elasticsearch Aggregation Query

The aggregation query in Elasticsearch is used to perform statistical analysis on the search results. It allows you to calculate metrics, generate histograms, and more. Aggregations are a useful tool for data analysis in Elasticsearch. Here’s an example of an aggregation query in Elasticsearch:

{
  "aggs": {
    "average_price": {
      "avg": {
        "field": "price"
      }
    }
  }
}

In this example, we are calculating the average value of the “price” field in the search results.

Exploring Different Query Types in Elasticsearch

Now that we have covered the various query types supported by Elasticsearch, let’s explore how these query types can be combined and used in different scenarios.

Related Article: Troubleshooting 502 Bad Gateway Nginx

Performing Search Queries in Elasticsearch

To perform a search query in Elasticsearch, you can use the Search API. The Search API allows you to specify the search query, the index or indices to search in, and additional options such as sorting and pagination. Here’s an example of how to perform a search query in Elasticsearch using the Search API:

POST /my_index/_search
{
  "query": {
    "match": {
      "title": "Elasticsearch"
    }
  }
}

In this example, we are searching for documents in the “my_index” index that have the term “Elasticsearch” in the “title” field.

Understanding Elasticsearch Query DSL

Elasticsearch Query DSL (Domain-Specific Language) is a useful way to express complex queries in Elasticsearch. It provides a flexible and expressive syntax for constructing search and filter queries. The Query DSL allows you to combine multiple queries, apply filters, and perform aggregations. Here’s an example of a search query using the Query DSL:

{
  "query": {
    "bool": {
      "must": [
        { "match": { "title": "Elasticsearch" } },
        { "range": { "price": { "gte": 100 } } }
      ],
      "must_not": [
        { "term": { "status": "out_of_stock" } }
      ]
    }
  }
}

In this example, we are using the bool query to combine a match query and a range query, and applying a must_not filter to exclude documents with a specific status.

Handling Full-Text Search in Elasticsearch

Full-text search is a common use case in Elasticsearch. It allows you to search for documents based on the presence of specific terms or phrases in the indexed data. Elasticsearch provides several features for handling full-text search, including tokenization, stemming, and relevance scoring. Here’s an example of a full-text search query in Elasticsearch:

{
  "query": {
    "match": {
      "content": "elasticsearch tutorial"
    }
  }
}

In this example, we are searching for documents that contain the terms “elasticsearch” and “tutorial” in the “content” field.

Related Article: How to Do Sorting in C++ & Sorting Techniques

Performing a Term Query in Elasticsearch

The term query in Elasticsearch is used to search for exact matches of terms in the indexed data. It can be useful for searching for specific values in fields that are not analyzed, such as keyword fields. Here’s an example of a term query in Elasticsearch:

{
  "query": {
    "term": {
      "status": "published"
    }
  }
}

In this example, we are searching for documents that have the term “published” in the “status” field.

Syntax for a Match Query in Elasticsearch

The match query in Elasticsearch is a versatile query type that allows you to perform full-text searches, phrase searches, and more. It analyzes the search terms and matches them against the indexed data. Here’s an example of a match query in Elasticsearch:

{
  "query": {
    "match": {
      "title": "Elasticsearch tutorial"
    }
  }
}

In this example, we are searching for documents that have the phrase “Elasticsearch tutorial” in the “title” field.

Utilizing a Range Query in Elasticsearch

The range query in Elasticsearch is used to search for documents that fall within a specified range of values. It can be used to search for numeric, date, or string values. Here’s an example of a range query in Elasticsearch:

{
  "query": {
    "range": {
      "price": {
        "gte": 100,
        "lte": 500
      }
    }
  }
}

In this example, we are searching for documents where the “price” field is greater than or equal to 100 and less than or equal to 500.

Related Article: How to Use JSON Parse and Stringify in JavaScript

Purpose of a Bool Query in Elasticsearch

The bool query in Elasticsearch allows you to combine multiple queries using boolean operators such as must, should, and must_not. It provides a useful way to express complex search criteria. Here’s an example of a bool query in Elasticsearch:

{
  "query": {
    "bool": {
      "must": [
        { "match": { "title": "Elasticsearch" } },
        { "range": { "price": { "gte": 100 } } }
      ],
      "must_not": [
        { "term": { "status": "out_of_stock" } }
      ]
    }
  }
}

In this example, we are searching for documents where the “title” field contains the term “Elasticsearch” and the “price” field is greater than or equal to 100, excluding documents that have the “status” field set to “out_of_stock”.

Filtering Results with a Query in Elasticsearch

Filter queries in Elasticsearch are used to narrow down the search results based on specific criteria. Unlike search queries, filter queries do not affect the relevance score of the documents. Here’s an example of a filter query in Elasticsearch:

{
  "query": {
    "bool": {
      "filter": [
        { "term": { "category": "electronics" } },
        { "range": { "price": { "gte": 100 } } }
      ]
    }
  }
}

In this example, we are searching for documents that have the “category” field set to “electronics” and the “price” field greater than or equal to 100.

Introduction to Aggregation Queries in Elasticsearch

Aggregation queries in Elasticsearch are used to perform statistical analysis on the search results. They allow you to calculate metrics, generate histograms, and more. Aggregations are a useful tool for data analysis in Elasticsearch. Here’s an example of an aggregation query in Elasticsearch:

{
  "aggs": {
    "average_price": {
      "avg": {
        "field": "price"
      }
    }
  }
}

In this example, we are calculating the average value of the “price” field in the search results.

Related Article: How to Implement Min Heap Binary Trees

Additional Resources

Introduction to Elasticsearch Queries
Query and Filter Context in Elasticsearch
Elasticsearch Query DSL – Introduction

You May Also Like

The most common wastes of software development (and how to reduce them)

Software development is a complex endeavor that requires much time to be spent by a highly-skilled, knowledgeable, and educated team of people. Often, there are time... read more

Agile Shortfalls and What They Mean for Developers

What is the best software development methodology to use? This question is the topic of hot debate during the project implementation stage. However, what you choose... read more

7 Shared Traits of Ineffective Engineering Teams

Why is your engineering team ineffective? In this article you will learn to recognize seven bad team traits. Ineffective engineering teams are not all the same, and the... read more

24 influential books programmers should read

The fast-paced world of programming demands that people remain up-to-date. In fact, getting ahead of the curve makes a programmer stand out in his professional field.... read more

How To Use A Regex To Only Accept Numbers 0-9

Learn how to validate and accept only numbers from 0 to 9 using a regex pattern. Implementing this pattern in your code will ensure that no characters are accepted,... read more

How To Distinguish Between POST And PUT In HTTP

Learn the difference between POST and PUT methods in HTTP and how to use them. Understand why the distinction between POST and PUT is important and explore best... read more