Run a search

edit

You can use the search API to search data stored in one or more Elasticsearch indices.

The API can runs two types of searches, depending on how you provide queries:

URI searches
Queries are provided through a query parameter. URI searches tend to be simpler and best suited for testing.
Request body searches
Queries are provided through the JSON body of the API request. These queries are written in Query DSL. We recommend using request body searches in most production use cases.

If you specify a query in both the URI and request body, the search API request runs only the URI query.

Run a URI search

edit

You can use the search API’s q query string parameter to run a search in the request’s URI. The q parameter only accepts queries written in Lucene’s query string syntax.

Example

To get started, ingest or add some data to an Elasticsearch index.

The following bulk API request adds some example user log data to the user_logs_000001 index.

PUT /user_logs_000001/_bulk?refresh
{"index":{"_index" : "user_logs_000001", "_id" : "1"}}
{ "@timestamp": "2020-12-06T11:04:05.000Z", "user": { "id": "vlb44hny" }, "message": "Login attempt failed" }
{"index":{"_index" : "user_logs_000001", "_id" : "2"}}
{ "@timestamp": "2020-12-07T11:06:07.000Z", "user": { "id": "8a4f500d" }, "message": "Login successful" }
{"index":{"_index" : "user_logs_000001", "_id" : "3"}}
{ "@timestamp": "2020-12-07T11:07:08.000Z", "user": { "id": "l7gk7f82" }, "message": "Logout successful" }

You can now use the search API to run a URI search on this index.

The following URI search matches documents with a user.id value of l7gk7f82. Note the query is specified using the q query string parameter.

GET /user_logs_000001/_search?q=user.id:8a4f500d

The API returns the following response. Note the hits.hits property contains the document that matched the query.

{
  "took": 2,
  "timed_out": false,
  "_shards": {
    "total": 1,
    "successful": 1,
    "skipped": 0,
    "failed": 0
  },
  "hits": {
    "total": {
      "value": 1,
      "relation": "eq"
    },
    "max_score": 0.9808291,
    "hits": [
      {
        "_index": "user_logs_000001",
        "_type": "_doc",
        "_id": "2",
        "_score": 0.9808291,
        "_source": {
          "@timestamp": "2020-12-07T11:06:07.000Z",
          "user": {
            "id": "8a4f500d"
          },
          "message": "Login successful"
        }
      }
    ]
  }
}

Run a request body search

edit

You can use the search API’s query request body parameter to provide a query as a JSON object, written in Query DSL.

Example

The following request body search uses the match query to match documents with a message value of login successful. Note the match query is specified as a JSON object in the query parameter.

GET /user_logs_000001/_search
{
  "query": {
    "match": {
      "message": "login successful"
    }
  }
}

The API returns the following response.

The hits.hits property contains matching documents. By default, the response sorts these matching documents by _score, a relevance score that measures how well each document matches the query.

{
  "took": 1,
  "timed_out": false,
  "_shards": {
    "total": 1,
    "successful": 1,
    "skipped": 0,
    "failed": 0
  },
  "hits": {
    "total": {
      "value": 3,
      "relation": "eq"
    },
    "max_score": 0.9983525,
    "hits": [
      {
        "_index": "user_logs_000001",
        "_type": "_doc",
        "_id": "2",
        "_score": 0.9983525,
        "_source": {
          "@timestamp": "2020-12-07T11:06:07.000Z",
          "user": {
            "id": "8a4f500d"
          },
          "message": "Login successful"
        }
      },
      {
        "_index": "user_logs_000001",
        "_type": "_doc",
        "_id": "3",
        "_score": 0.49917626,
        "_source": {
          "@timestamp": "2020-12-07T11:07:08.000Z",
          "user": {
            "id": "l7gk7f82"
          },
          "message": "Logout successful"
        }
      },
      {
        "_index": "user_logs_000001",
        "_type": "_doc",
        "_id": "1",
        "_score": 0.42081726,
        "_source": {
          "@timestamp": "2020-12-06T11:04:05.000Z",
          "user": {
            "id": "vlb44hny"
          },
          "message": "Login attempt failed"
        }
      }
    ]
  }
}

Search multiple indices

edit

To search multiple indices, add them as comma-separated values in the search API request path.

Example

The following request searches the user_logs_000001 and user_logs_000002 indices.

GET /user_logs_000001,user_logs_000002/_search
{
  "query": {
    "match": {
      "message": "login successful"
    }
  }
}

You can also search multiple indices using an index pattern.

Example

The following request uses the index pattern user_logs* in place of the index name. The request searches any indices in the cluster that start with user_logs.

GET /user_logs*/_search
{
  "query": {
    "match": {
      "message": "login successful"
    }
  }
}

To search all indices in a cluster, omit the index name from the request path. Alternatively, you can use _all or * in place of the index name.

Example

The following requests are equivalent and search all indices in the cluster.

GET /_search
{
  "query": {
    "match": {
      "message": "login successful"
    }
  }
}

GET /_all/_search
{
  "query": {
    "match": {
      "message": "login successful"
    }
  }
}

GET /*/_search
{
    "query" : {
        "match" : { "message" : "login" }
    }
}

Paginate search results

edit

By default, the search API returns the top 10 matching documents.

To paginate through a larger set of results, you can use the search API’s size and from parameters. The size parameter is the number of matching documents to return. The from parameter is a zero-indexed offset from the beginning of the complete result set that indicates the document you want to start with.

Example

The following search API request sets the from offset to 5, meaning the request offsets, or skips, the first five matching documents.

The size parameter is 20, meaning the request can return up to 20 documents, starting at the offset.

GET /_search
{
  "from": 5,
  "size": 20,
  "query": {
    "term": {
      "user.id": "8a4f500d"
    }
  }
}

By default, you cannot page through more than 10,000 documents using the from and size parameters. This limit is set using the index.max_result_window index setting.

Deep paging or requesting many results at once can result in slow searches. Results are sorted before being returned. Because search requests usually span multiple shards, each shard must generate its own sorted results. These separate results must then be combined and sorted to ensure that the overall sort order is correct.

As an alternative to deep paging, we recommend using scroll or the search_after parameter.

Elasticsearch uses Lucene’s internal doc IDs as tie-breakers. These internal doc IDs can be completely different across replicas of the same data. When paginating, you might occasionally see that documents with the same sort values are not ordered consistently.

Retrieve selected fields

edit

By default, each hit in the search response includes the document _source, which is the entire JSON object that was provided when indexing the document. If you only need certain source fields in the search response, you can use the source filtering to restrict what parts of the source are returned.

Returning fields using only the document source has some limitations:

  • The _source field does not include multi-fields or field aliases. Likewise, a field in the source does not contain values copied using the copy_to mapping parameter.
  • Since the _source is stored as a single field in Lucene, the whole source object must be loaded and parsed, even if only a small number of fields are needed.

To avoid these limitations, you can:

  • Use the docvalue_fields parameter to get values for selected fields. This can be a good choice when returning a fairly small number of fields that support doc values, such as keywords and dates.
  • Use the stored_fields parameter to get the values for specific stored fields. (Fields that use the store mapping option.)

You can find more detailed information on each of these methods in the following sections:

Source filtering

edit

You can use the _source parameter to select what fields of the source are returned. This is called source filtering.

Example

The following search API request sets the _source request body parameter to false. The document source is not included in the response.

GET /_search
{
  "_source": false,
  "query": {
    "term": {
      "user.id": "8a4f500d"
    }
  }
}

To return only a subset of source fields, specify a wildcard (*) pattern in the _source parameter. The following search API request returns the source for only the obj field and its properties.

GET /_search
{
  "_source": "obj.*",
  "query": {
    "term": {
      "user.id": "8a4f500d"
    }
  }
}

You can also specify an array of wildcard patterns in the _source field. The following search API request returns the source for only the obj1 and obj2 fields and their properties.

GET /_search
{
  "_source": [ "obj1.*", "obj2.*" ],
  "query": {
    "term": {
      "user.id": "8a4f500d"
    }
  }
}

For finer control, you can specify an object containing arrays of includes and excludes patterns in the _source parameter.

If the includes property is specified, only source fields that match one of its patterns are returned. You can exclude fields from this subset using the excludes property.

If the includes property is not specified, the entire document source is returned, excluding any fields that match a pattern in the excludes property.

The following search API request returns the source for only the obj1 and obj2 fields and their properties, excluding any child description fields.

GET /_search
{
  "_source": {
    "includes": [ "obj1.*", "obj2.*" ],
    "excludes": [ "*.description" ]
  },
  "query": {
    "term": {
      "user.id": "8a4f500d"
    }
  }
}

Doc value fields

edit

You can use the docvalue_fields parameter to return doc values for one or more fields in the search response.

Doc values store the same values as the _source but in an on-disk, column-based structure that’s optimized for sorting and aggregations. Since each field is stored separately, Elasticsearch only reads the field values that were requested and can avoid loading the whole document _source.

Doc values are stored for supported fields by default. However, doc values are not supported for text or text_annotated fields.

Example

The following search request uses the docvalue_fields parameter to retrieve doc values for the following fields:

  • Fields with names starting with my_ip
  • my_keyword_field
  • Fields with names ending with _date_field
GET /_search
{
  "query": {
    "match_all": {}
  },
  "docvalue_fields": [
    "my_ip*",                     
    {
      "field": "my_keyword_field" 
    },
    {
      "field": "*_date_field",
      "format": "epoch_millis"    
    }
  ]
}

Wildcard patten used to match field names, specified as a string.

Wildcard patten used to match field names, specified as an object.

With the object notation, you can use the format parameter to specify a format for the field’s returned doc values. Date fields support a date format. Numeric fields support a DecimalFormat pattern. Other field datatypes do not support the format parameter.

You cannot use the docvalue_fields parameter to retrieve doc values for nested objects. If you specify a nested object, the search returns an empty array ([ ]) for the field. To access nested fields, use the inner_hits parameter’s docvalue_fields property.

Stored fields

edit

It’s also possible to store an individual field’s values by using the store mapping option. You can use the stored_fields parameter to include these stored values in the search response.