AI Hints
Home›Elasticsearch Tutorial›Scan, FastAPI and a Search Service
Elasticsearch · Lesson 94 of 120

Scanning Every Document

Read them all.

⏱ 2 min read▶ Video at 1:28:12🎓 Free
Watch this lesson in the Elasticsearch courseWatch on YouTube ↗Full Elasticsearch course

Sometimes you need every document, like exporting all orders to a spreadsheet. A normal search stops at ten thousand results. The scan helper pages through everything for you.

  • Export everything
  • Search stops at 10,000
  • helpers.scan

Export every order

Scan takes a query, and yields every matching document, page by page. We count them, and add up revenue for Canada. Run it. All three hundred and seventy four Canadian orders, read one by one.

export.pypython
from elasticsearch import Elasticsearch

es = Elasticsearch("http://localhost:9200")
from elasticsearch import helpers

count, revenue = 0, 0.0
for hit in helpers.scan(es, index="orders",
                        query={"query": {"term": {"country": "CA"}}}):
    count += 1
    revenue += hit["_source"]["total"]

print(count, "orders, revenue", round(revenue, 2))
Output
374 orders, revenue 102309.1
Also uses _load
orders

scan notes

Scan uses a point in time and search after under the hood. Results aren't sorted, which keeps it fast. It's great for exports, migrations and backfills. For totals alone, an aggregation is much faster.

keyvalue
Under the hoodPIT + search_after
Orderunsorted, fast
Useexports, migrations
Just totals?use an aggregation

Summary

The scan helper streams every matching document, for exports and migrations. Next, a search API with FastAPI.

Key takeaways
  • helpers.scan
  • Every document
  • Exports
Next up: A Search API with FastAPI — a web API for search