0
0
Elasticsearchquery~5 mins

Saved searches and filters in Elasticsearch

Choose your learning style9 modes available
Introduction

Saved searches and filters help you quickly find the same data again without typing the search every time.

You want to reuse a search query often without rewriting it.
You need to share a specific search with your team.
You want to apply the same filter to different dashboards or reports.
You want to save time by not building complex queries repeatedly.
Syntax
Elasticsearch
POST /_search/template
{
  "id": "my_saved_search",
  "params": {
    "filter_value": "example"
  }
}

Saved searches are stored as search templates with an ID.

You can pass parameters to customize the saved search when running it.

Examples
This saves a search template named my_saved_search that looks for a message matching a value you provide.
Elasticsearch
PUT /_scripts/my_saved_search
{
  "script": {
    "lang": "mustache",
    "source": "{\"query\":{\"match\":{\"message\":\"{{filter_value}}\"}}}"
  }
}
This runs the saved search with the filter value set to "error".
Elasticsearch
POST /_search/template
{
  "id": "my_saved_search",
  "params": {
    "filter_value": "error"
  }
}
This example shows a filter that finds documents where status is active and age is 30 or more.
Elasticsearch
GET /my-index/_search
{
  "query": {
    "bool": {
      "filter": [
        { "term": { "status": "active" } },
        { "range": { "age": { "gte": 30 } } }
      ]
    }
  }
}
Sample Program

This program first saves a search template that looks for documents with a title matching a term you give. Then it runs that saved search with the term "Elasticsearch".

Elasticsearch
PUT /_scripts/saved_search_example
{
  "script": {
    "lang": "mustache",
    "source": "{\"query\":{\"match\":{\"title\":\"{{search_term}}\"}}}"
  }
}

POST /_search/template
{
  "id": "saved_search_example",
  "params": {
    "search_term": "Elasticsearch"
  }
}
OutputSuccess
Important Notes

Saved searches are stored as scripts or templates in Elasticsearch.

You can update saved searches anytime by changing the script.

Filters help narrow down results without changing the main query.

Summary

Saved searches let you reuse queries easily.

Filters help focus on specific data in your searches.

You run saved searches by calling their ID and passing parameters.