Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Introduction to Advanced Search

What is Elasticsearch?

Elasticsearch is a powerful open-source search and analytics engine that is designed for horizontal scalability, reliability, and real-time search capabilities. It is based on Apache Lucene and provides a distributed, full-text search engine that is capable of handling large volumes of data with low latency.

Why Use Advanced Search?

Advanced search functionalities allow users to perform complex queries and retrieve precise results from large datasets. This is particularly useful in scenarios where simple keyword searches are insufficient, and you need to filter, sort, and analyze data more deeply.

Basic Query Example

Let's start with a basic query to search for documents that contain the word "Elasticsearch".

GET /_search
{
  "query": {
    "match": {
      "message": "Elasticsearch"
    }
  }
}

Using Filters

Filters in Elasticsearch allow you to restrict the search results to documents that match certain criteria. Here's an example of a filtered query:

GET /_search
{
  "query": {
    "bool": {
      "must": { "match": { "message": "Elasticsearch" }},
      "filter": { "term": { "status": "active" }}
    }
  }
}

Sorting Results

Sorting in Elasticsearch allows you to order the search results based on one or more fields. Here's an example of a query that sorts the results by a timestamp field:

GET /_search
{
  "query": {
    "match": {
      "message": "Elasticsearch"
    }
  },
  "sort": [
    {"timestamp": {"order": "desc"}}
  ]
}

Aggregation Queries

Aggregations in Elasticsearch allow you to perform complex data analysis and summarization operations. Here's an example of an aggregation query that calculates the average response time:

GET /_search
{
  "query": {
    "match_all": {}
  },
  "aggs": {
    "avg_response_time": {
      "avg": { "field": "response_time" }
    }
  }
}

Combining Multiple Queries

You can combine multiple types of queries using the bool query. Here's an example:

GET /_search
{
  "query": {
    "bool": {
      "must": { "match": { "message": "Elasticsearch" }},
      "filter": { "term": { "status": "active" }},
      "should": [
        { "range": { "age": { "gt": 30 }}},
        { "term": { "premium": true }}
      ]
    }
  }
}