0
0
ElasticsearchHow-ToBeginner · 4 min read

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, usually AND or OR.
  • 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_string for user input without validation, which can lead to errors or unexpected results.
  • Confusing query_string with match query; query_string expects a query syntax string, while match expects 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

ParameterDescriptionExample
queryThe search string with operators"Elasticsearch AND tutorial"
fieldsList of fields to search["title", "content"]
default_operatorOperator between terms (AND/OR)"AND"
analyze_wildcardAnalyze wildcard termstrue
allow_leading_wildcardAllow wildcards at startfalse (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.