# Text Indexing in ElasticSearch, MongoDB and UDisk

> Comparing indexing performance of ElasticSearch, MongoDB, and UDisk on a 20GB text dataset, revealing the massive overhead of Java-based search engines.

[Blog](https://www.unum.cloud/blog.md) [IO](https://www.unum.cloud/blog?tag=IO)

Comparing indexing performance of ElasticSearch, MongoDB, and UDisk on a 20GB text dataset, revealing the massive overhead of Java-based search engines.

- By

  Ash Vardanian

- Published

  Jan 3, 2021

Most of the data that flows into our analytical pipelines originally has textual form. Afterwards it transforms into a more structured representation, but we often re-evaluate the same context once more related data arrives. At such times it’s crucial to fetch all the occurrences of a specific string or RegEx pattern, so we need a fast text index!

At Unum, we develop a neuro-symbolic AI. The symbolic half of it lives in [graphs](https://www.unum.cloud/blog/graphs.md), and the raw material for those graphs is text: papers, posts, encyclopedia articles. Every time a model learns a new concept, we want to go back and find every document that mentions it. So we took the two most popular ways to search text on a single machine and put them next to our own storage engine, UDisk.

[Reproduce Our Results](https://github.com/unum-cloud/RegExum)

## Why Text Is a Storage Problem

It’s tempting to think that search is a CPU problem. Tokenize the text, build an index, intersect a few lists, done. In practice, the CPU is rarely the bottleneck. A laptop CPU can scan gigabytes of text per second, but a consumer NVMe drive like the Samsung 970 EVO Plus is [rated](https://www.samsung.com/semiconductor/minisite/ssd/product/consumer/970evoplus/) for 3.5 GB/s of sequential reads, and that number collapses once the reads become small and random. Text indexes are the worst case here. Every new document touches one posting list per distinct word, and those lists are scattered all over the disk.

The same drive is rated for 600 TB of total writes over its lifetime at the 1 TB capacity. That sounds like a lot, until your database multiplies every incoming byte by 87, as one of the contenders below does. This is why we track three things in every benchmark below: the speed, the size of the resulting index, and the number of bytes that hit the disk to get there.

## Setup

### Datasets

- [Covid 19](https://www.kaggle.com/allen-institute-for-ai/CORD-19-research-challenge) Scientific Papers.

  - Documents: 45,941.
  - Sections: 1,604,649.
  - Size: 1,7 GB.

- [Political Tweets India](https://www.kaggle.com/iamyoginth/facthub) Posts.

  - Documents: 12,488,144.
  - Sections: 12,488,144.
  - Size: 2,3 GB.

- [English Wikipedia](https://www.kaggle.com/jkkphys/english-wikipedia-articles-20170820-sqlite) Dump from 2017.

  - Documents: 4,902,648.
  - Sections: 23,046,187.
  - Size: 18,2 GB.

The three were picked for their shapes, not their topics. Covid19 has few, long documents, averaging around 1 KB per section. The tweets are the opposite: over 12 million tiny records of about 184 bytes each. Wikipedia is simply big, larger than the RAM of the machine. Every dataset is a CSV with `article_id`, `article_title`, `section_title` and `section_text` columns, and every section becomes a separate searchable record.

### Device

- CPU:

  - Model: `Intel(R) Core(TM) i9-9880H CPU @ 2.30GHz`.
  - Cores: 8 (16 threads @ 2.3 Ghz).

- RAM Space: 16.0 GB.

- Disk Space: 931.5 GB.

- OS Family: Darwin.

- Python Version: 3.7.7.

Databases were configured to use 512 MB of RAM for cache and 4 cores for query execution.

Yes, this is a MacBook Pro. A laptop is what most data scientists start with, and it is the harshest environment for a database: little RAM, one SSD, and a thermal envelope that doesn’t forgive wasted work.

### Contenders

- **MongoDB** Community 4.2, installed from Homebrew. Documents are stored in WiredTiger, and the text content gets a [`text` index](https://docs.mongodb.com/manual/core/index-text/), which tokenizes, drops stop-words and stems English words. We talk to it with PyMongo and import in batches of 10,000 documents.
- **ElasticSearch** 7, also from Homebrew, with a single shard. It is a Java server built around Apache Lucene, and the text field uses the standard analyzer. We import with the `streaming_bulk` helper of the official Python client.
- **UDisk**, our own engine, written in C++. Unlike the other two, it is embedded: the Python process calls it directly, with no socket in between.

That last point deserves a remark. A client-server database pays for serialization and a network round-trip on every call, even on `localhost`. During the Covid19 import alone, the MongoDB and ElasticSearch clients pushed 1.4 GB and 1.7 GB respectively through the loopback interface. We consider that overhead part of the product: if your database only speaks HTTP and JSON, you pay for HTTP and JSON.

### Methodology

The harness is a small Python library that hides every database behind the same interface, so the exact same benchmark function runs against each of them. All the “random” work is sampled from the dataset before the timer starts, so every engine receives identical queries:

- **Import**: load the entire CSV into an empty database and count the records.
- **Lookups**: fetch 1,000 random records by their identifier.
- **Word search**: find up to 20 records containing a random short word of 7–8 letters, or a long word of 10+ letters. Another variant asks for up to 10,000 matches.
- **Phrase search**: the same, but with two random words joined by a space.
- **Upserts and removals**: 1,000 random records, either one-by-one or in batches of 500.

Every search benchmark runs until it exhausts its 10,000 queries or 30 seconds pass, whichever comes first. Beyond time, we record the bytes read from and written to disk during every benchmark, using the operating system’s I/O counters.

## Sequential Writes: Import CSV (docs/sec)

Every datascience project starts by importing the data. Let’s see how long it will take to load every dataset into each DB.

| | Covid19 | PoliticalTweetsIndia | Gains |
| - | - | - | - |
| MongoDB | 398.40 | 3,301.61 | 1x |
| ElasticSearch | 5,915.53 | 10,262.29 | 8.98x |
| UDisk | 142,575.07 | 930,285.22 | **319.82x** |

| | Covid19 | PoliticalTweetsIndia |
| - | - | - |
| MongoDB | 1 hours, 7 mins | 50 mins, 29 secs |
| ElasticSearch | 4 mins, 31 secs | 16 mins, 14 secs |
| UDisk | 0 mins, 11 secs | 0 mins, 13 secs |

A few notes on how to read those tables. The unit is records, and for Covid19 a record is a section, not a paper: 1.6 million sections at 398 per second is exactly the hour and 7 minutes MongoDB spent. The “Gains” column is the speedup over MongoDB, averaged across both datasets. UDisk is 358x faster than MongoDB on the papers and 282x faster on the tweets, hence the 320x. Against ElasticSearch, the gap is 24x on the long papers and 91x on the short tweets.

> The MongoDB and ElasticSearch runs on PoliticalTweetsIndia were logged with 10 million imported records, while UDisk imported all 12.5 million. Throughput is normalized per record, so the first table is unaffected, but the wall-clock times for those two cover a smaller workload.

Those benchmarks only tell half of the story. We should not only consider performance, but also the used disk space and the affect on the hardware lifetime, as SSDs don’t last too long. MongoDB generally performs well across different benchmarks, but it failed to import the English Wikipedia in 10 hours. I suspect a bug in the implementation of the text index, as some batch import operations took over 10 mins for a modest batch size of 10,000 docs. Even at its Covid19 pace of roughly 400 sections per second, the 23 million Wikipedia sections would need about 16 hours.

| | Covid19 | PoliticalTweetsIndia | EnglishWikipedia |
| - | - | - | - |
| MongoDB | 1,9 GB | 3,2 GB | Expected 60,7 GB |
| ElasticSearch | 2,5 GB | 2,9 GB | 33,5 GB |

The final footprint is reasonable for both: between 1.1x and 1.5x of the raw CSV on the smaller datasets. English Wikipedia is where it starts to hurt, with 33.5 GB for ElasticSearch and a projected 60.7 GB for MongoDB, 1.8x and 3.3x of the input.

Import overhead gigabytes written to disk

| gigabytes written to disk | MongoDB | ElasticSearch | UDisk |
| - | - | - | - |
| Covid19 | 147.3 GB | 9.9 GB | 1.6 GB |
| PoliticalTweetsIndia | 74.9 GB | 20.0 GB | 2.0 GB |

The index size is what you see. The bytes written are what you pay. To build that 1.9 GB index for Covid19, MongoDB wrote 147 GB to the SSD, about 87 times the size of the input. Per record, that is 92 KB of writes for a section that averages around 1 KB. ElasticSearch wrote 6.2 KB per section, and UDisk wrote 1.0 KB, roughly the size of the data itself. The tweets tell the same story: 7.5 KB per tweet for MongoDB, 2.0 KB for ElasticSearch, and 161 bytes for UDisk, for tweets that average 184 bytes.

Reads show the same pattern. While importing 1.7 GB of papers, MongoDB read 32.4 GB back from the disk, ElasticSearch 6.0 GB, and UDisk 0.7 GB. An index that keeps re-reading and re-writing its own pages is exactly the kind of workload that kills SSDs. With a 600 TB write budget, the 970 EVO Plus we mentioned above would survive only about 4,000 MongoDB imports of the Covid19 dataset. That sounds like a lot until you remember that production systems re-index constantly.

## Queries and Updates

Importing is only the first step. Once the data is in, you want to search it and keep it fresh. Here are the rest of the results from the same run, in records or queries per second, for Covid19 and PoliticalTweetsIndia, separated by a slash.

| Reads | MongoDB | ElasticSearch | UDisk |
| - | - | - | - |
| Lookup by ID | 1,717.84 / 1,147.71 | 760.71 / 615.10 | 1,819.77 / 1,277.94 |
| Up to 10,000 with short word | 1.68 / 0.86 | 0.57 / 0.54 | 1.16 / 0.99 |
| Up to 20 with short word | 201.39 / 85.02 | 396.55 / 276.26 | 119.09 / 53.76 |
| Up to 20 with long word | 187.99 / 24.65 | 594.84 / 485.05 | 106.75 / 15.73 |
| Up to 20 with short phrase | 0.21 / 0.63 | 353.87 / 434.69 | 5.92 / 7.27 |
| Up to 20 with long phrase | 0.30 / 0.11 | 540.17 / 678.58 | 7.59 / 10.14 |

| Writes | MongoDB | ElasticSearch | UDisk |
| - | - | - | - |
| Upsert one | 230.38 / 963.17 | 28.80 / 26.33 | 1,062.47 / 937.12 |
| Upsert batch of 500 | 232.33 / 2,127.89 | 45.80 / 45.90 | 1,122.76 / 1,011.04 |
| Remove one | 56.65 / 271.21 | 24.47 / 22.36 | 1,045.84 / 935.42 |
| Remove batch of 500 | 226.21 / 2,575.94 | 42.55 / 44.84 | 1,101.05 / 1,005.76 |

This is where it gets more nuanced, and we would rather show it than hide it.

**Lookups by ID** are a wash between MongoDB and UDisk, and ElasticSearch is 2x slower. Fetching one record is cheap everywhere, so what you measure is mostly the cost of the call itself, and a JSON-over-HTTP request is the most expensive one.

**Word search** is where ElasticSearch shines, being 2.6x faster than MongoDB on short words and 11.4x on long ones. This is exactly what Lucene was built for. An inverted index maps every token to a sorted list of records, and fetching the first 20 entries of that list is nearly free. UDisk is at 0.6x of MongoDB here, and we have work to do. Asking for 10,000 matches instead of 20 brings everyone down to around one query per second, as the cost moves from finding the matches to shipping them.

**Phrase search** is the opposite story for MongoDB. Its text index knows which documents contain each word, but not where, so to confirm that two words stand next to each other it has to go back and check the documents themselves. Only 5 to 20 phrase queries completed in each 30-second window. UDisk handles phrases 20x to 57x faster than MongoDB. ElasticSearch posts the best numbers of all, but with a caveat: our harness sends it a `match` query with the `and` operator, which only requires both words to be present anywhere in the record. That is a simpler question than the exact phrase the other two had to answer.

**Updates** are where UDisk is most consistent: around 1,000 records per second for single and batched upserts and removals, on both datasets. MongoDB is fast on the tiny tweets, especially in batches, reaching 2,576 removals per second, but single removals drop to 57 per second on the larger papers. ElasticSearch sits at 22–46 per second across the board. Part of that is on us: after every write, our harness refreshes the index, so that the next query is guaranteed to see the change. By default, ElasticSearch only refreshes once a second, which would make the writes faster but leave the fresh data invisible to search in the meantime. Each refresh creates a new Lucene segment, and the SSD pays for it: a thousand single-record removals cost ElasticSearch over 2 GB of writes on either dataset.

## What We Learned

No database wins everything, and anyone claiming otherwise is selling something. Here is our honest summary for a single machine at the end of 2020:

1. For bulk imports and updates, UDisk is in a different league: orders of magnitude faster, and writing roughly as many bytes as it receives, where the others multiply them by 6x to 87x.
2. For “top 20 documents with this word” queries, ElasticSearch and its inverted index remain the ones to beat.
3. MongoDB is a good general-purpose document store, but its text index is an afterthought: slow to build, heavy on the disk and nearly unusable for phrases.

The biggest datasets are also the ones where the old engines struggle most. Wikipedia was the only dataset larger than RAM, and one of the two failed to import it within 10 hours.

What comes next? Our harness already contains RegEx workloads that we haven’t published yet: phone numbers, e-mails, dates, times, IP addresses and XML tags, each combined with a random word to avoid cache hits. That is where we expect the gap to be widest, as inverted indexes are built around whole tokens, and patterns like these cross token boundaries. After that, we want mixed multi-threaded reads and writes, which are closer to real production, and a full English Wikipedia run on a server-grade machine. Until then, the benchmark is open, so feel free to reproduce the numbers on your own hardware.
