0
0
Elasticsearchquery~5 mins

Source filtering in Elasticsearch - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Source filtering
O(n)
Understanding Time Complexity

When using source filtering in Elasticsearch, we want to know how the time to get results changes as we ask for more or fewer fields.

We ask: How does filtering the source affect the work Elasticsearch does?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


GET /my_index/_search
{
  "_source": ["title", "author"],
  "query": {
    "match_all": {}
  }
}
    

This code asks Elasticsearch to return only the "title" and "author" fields from all documents.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Elasticsearch reads each matching document and extracts requested fields.
  • How many times: Once per matching document in the search results.
How Execution Grows With Input

As the number of matching documents grows, Elasticsearch extracts fields from each one.

Input Size (n)Approx. Operations
10Extract fields from 10 documents
100Extract fields from 100 documents
1000Extract fields from 1000 documents

Pattern observation: The work grows directly with the number of documents returned.

Final Time Complexity

Time Complexity: O(n)

This means the time to filter source fields grows linearly with the number of documents returned.

Common Mistake

[X] Wrong: "Filtering source fields makes the search run faster regardless of result size."

[OK] Correct: Filtering reduces data sent back but Elasticsearch still reads each matching document, so time depends on how many documents are returned.

Interview Connect

Understanding how source filtering affects performance helps you explain trade-offs in real projects where you want less data but still need fast responses.

Self-Check

What if we changed the source filter to include all fields instead of just a few? How would the time complexity change?