How to Use query_string in Elasticsearch for Flexible Searches
Use the
query_string query in Elasticsearch to search text with operators like AND, OR, and wildcards. It allows searching multiple fields and supports complex search expressions in a single query string.Syntax
The query_string query uses a single string to define the search criteria. It supports operators like AND, OR, NOT, wildcards (*, ?), and field-specific searches.
Key parts:
query: The search expression string.fields: Optional list of fields to search.default_operator: Operator between terms, usuallyANDorOR.analyze_wildcard: Whether to analyze wildcard terms.
json
{
"query": {
"query_string": {
"query": "search terms AND another",
"fields": ["title", "content"],
"default_operator": "AND",
"analyze_wildcard": true
}
}
}Example
This example searches for documents where the title or content fields contain the word Elasticsearch and also the word tutorial. The AND operator ensures both words must be present.
json
{
"query": {
"query_string": {
"query": "Elasticsearch AND tutorial",
"fields": ["title", "content"],
"default_operator": "AND"
}
}
}Output
{
"hits": {
"total": 2,
"hits": [
{"_id": "1", "_source": {"title": "Elasticsearch tutorial", "content": "Learn Elasticsearch basics."}},
{"_id": "3", "_source": {"title": "Advanced Elasticsearch", "content": "Tutorial for experts."}}
]
}
}
Common Pitfalls
Common mistakes when using query_string include:
- Not escaping special characters like
+,-,:, which can cause syntax errors. - Using
query_stringfor user input without validation, which can lead to errors or unexpected results. - Confusing
query_stringwithmatchquery;query_stringexpects a query syntax string, whilematchexpects plain text.
Wrong example: Unescaped special characters causing error:
json
{
"query": {
"query_string": {
"query": "title:Elasticsearch+tutorial"
}
}
}
// Corrected by escaping '+' as '\\+':
{
"query": {
"query_string": {
"query": "title:Elasticsearch\\+tutorial"
}
}
}Quick Reference
| Parameter | Description | Example |
|---|---|---|
| query | The search string with operators | "Elasticsearch AND tutorial" |
| fields | List of fields to search | ["title", "content"] |
| default_operator | Operator between terms (AND/OR) | "AND" |
| analyze_wildcard | Analyze wildcard terms | true |
| allow_leading_wildcard | Allow wildcards at start | false (default) |
Key Takeaways
Use
query_string to write flexible search queries with operators and field targeting.Always escape special characters in the query string to avoid syntax errors.
Prefer
query_string for complex queries and match for simple text searches.Specify
fields to limit search scope and improve performance.Validate or sanitize user input before using it in
query_string queries.