How to Search in Elasticsearch: Syntax and Examples
To search in Elasticsearch, use the
_search API with a JSON query body that defines your search criteria using the Query DSL. You send a POST or GET request to your index with a query like { "query": { "match": { "field": "value" } } } to find matching documents.Syntax
The basic syntax to search in Elasticsearch uses the _search endpoint on an index. You send a JSON body with a query object that describes what you want to find.
- HTTP method: Usually
GETorPOST - Endpoint:
/index_name/_search - Body: JSON with
querykey - Query types:
match,term,bool, etc.
json
{
"query": {
"match": {
"field_name": "search_value"
}
}
}Example
This example searches the products index for documents where the name field contains the word "phone".
json
POST /products/_search
{
"query": {
"match": {
"name": "phone"
}
}
}Output
{
"took": 5,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"skipped": 0,
"failed": 0
},
"hits": {
"total": {
"value": 3,
"relation": "eq"
},
"max_score": 1.0,
"hits": [
{
"_index": "products",
"_id": "1",
"_score": 1.0,
"_source": {
"name": "Smartphone X",
"price": 699
}
},
{
"_index": "products",
"_id": "2",
"_score": 0.9,
"_source": {
"name": "Phone Case",
"price": 19
}
},
{
"_index": "products",
"_id": "3",
"_score": 0.8,
"_source": {
"name": "Wireless Phone Charger",
"price": 49
}
}
]
}
}
Common Pitfalls
Common mistakes when searching in Elasticsearch include:
- Using
termquery for full-text search instead ofmatch, which causes no results becausetermlooks for exact values. - Not specifying the correct index or misspelling the index name.
- Forgetting to use JSON format in the request body.
- Ignoring case sensitivity and text analysis differences.
Example of wrong vs right query:
json
POST /products/_search
{
"query": {
"term": {
"name": "phone"
}
}
}
// This returns no results if "name" is analyzed text.
POST /products/_search
{
"query": {
"match": {
"name": "phone"
}
}
}
// This returns matching documents because it uses full-text search.Quick Reference
Here is a quick reference for common Elasticsearch search queries:
| Query Type | Description | Use Case |
|---|---|---|
| match | Full-text search with analysis | Search text fields for relevant matches |
| term | Exact value match without analysis | Search keyword or exact values |
| bool | Combine multiple queries with AND, OR, NOT | Complex queries with filters |
| range | Search within numeric or date ranges | Find documents in a range |
| exists | Check if a field has a value | Filter documents with a field present |
Key Takeaways
Use the _search API with a JSON query body to find documents in Elasticsearch.
Use the match query for full-text search and term query for exact matches.
Always specify the correct index and use valid JSON format in your requests.
Beware of text analysis differences that affect search results.
Combine queries with bool for more complex search conditions.