Search Engine Implementation in Java
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Search Engine runs in O(n log n) time and O(n) space, in Java as in every other language.
- ✓java.util.HashMap<String, List<int[]>> for postings, TreeMap when the term dictionary must be ordered, java.util.PriorityQueue for a bounded top-k.
- ✓computeIfAbsent(term, k -> new ArrayList<>()).add(p) instead of get / null-check / put, and merge(doc, delta, Double::sum) for score accumulation.
- ✓The Java trap: List<Integer> postings box every doc id. Integer.valueOf caches only -128..127, so ids above 127 each become a distinct heap object (a 12-byte header plus the 4-byte int, padded to 16 bytes) behind a 4-byte compressed-oops reference: a 10M-posting index that should be 40 MB of int[] becomes roughly 200 MB of scattered objects, and the merge chases pointers instead of streaming cache lines.
- ✓String caches its hashCode in a field, so the second and every later lookup of the same token skips rehashing entirely -- exactly the opposite of Go's map, and it makes a hot vocabulary nearly free.
What Search Engine actually is
Search Engine in Java: what you actually reach for
Java implementation
import java.util.*;
import java.util.regex.Pattern;
public final class InvertedIndex {
private static final Pattern SPLIT = Pattern.compile("[^\\p{L}\\p{N}]+");
// int[]{doc, tf} -- a List<Integer> would box every id
private final Map<String, List<int[]>> postings = new HashMap<>();
private final Map<Integer, Integer> lengths = new HashMap<>();
public void add(int docId, String text) {
Map<String, Integer> tf = new HashMap<>();
for (String t : SPLIT.split(text.toLowerCase(Locale.ROOT)))
if (!t.isEmpty()) tf.merge(t, 1, Integer::sum);
int len = 0;
for (int c : tf.values()) len += c;
lengths.put(docId, len);
tf.forEach((term, n) ->
postings.computeIfAbsent(term, k -> new ArrayList<>()).add(new int[]{docId, n}));
}
public List<Map.Entry<Integer, Double>> search(String query, int k) {
int n = lengths.size();
Map<Integer, Double> scores = new HashMap<>();
for (String term : SPLIT.split(query.toLowerCase(Locale.ROOT))) {
List<int[]> list = postings.get(term);
if (list == null) continue;
double idf = Math.log(1 + (n - list.size() + 0.5) / (list.size() + 0.5));
for (int[] p : list)
scores.merge(p[0], idf * p[1] / (p[1] + 1.2), Double::sum);
}
PriorityQueue<Map.Entry<Integer, Double>> top =
new PriorityQueue<>(Comparator.comparingDouble(Map.Entry::getValue));
for (Map.Entry<Integer, Double> e : scores.entrySet()) {
top.offer(e);
if (top.size() > k) top.poll();
}
List<Map.Entry<Integer, Double>> out = new ArrayList<>(top);
out.sort(Comparator.comparingDouble(
(Map.Entry<Integer, Double> e) -> e.getValue()).reversed());
return out;
}
}
Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Java-specific trap
Performance in Java, beyond the O(n log n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Java type or library should I use for Search Engine?
java.util.HashMap<String, List<int[]>> for postings, TreeMap when the term dictionary must be ordered, java.util.PriorityQueue for a bounded top-k. java.text.BreakIterator's getWordInstance(Locale) does dictionary-driven word segmentation for Thai that a regex cannot reproduce, and rule-based script-run breaking everywhere else -- real Japanese morphological segmentation still needs Lucene's Kuromoji analyzer; java.util.regex.Pattern with \p{L} and \p{N} classes handles the easy cases. Nothing in the JDK ranks documents -- Apache Lucene (org.apache.lucene.index.IndexWriter, org.apache.lucene.search.IndexSearcher, BM25Similarity) is the reference implementation that Elasticsearch and Solr both wrap.
What is the most common Java mistake when implementing Search Engine?
List<Integer> postings box every doc id. Integer.valueOf caches only -128..127, so ids above 127 each become a distinct heap object (a 12-byte header plus the 4-byte int, padded to 16 bytes) behind a 4-byte compressed-oops reference: a 10M-posting index that should be 40 MB of int[] becomes roughly 200 MB of scattered objects, and the merge chases pointers instead of streaming cache lines. Worse, id1 == id2 compares references, so it quietly works across your first 128 test documents and starts returning false in production. Store int[] chunks, or a primitive collection library.
How does Search Engine actually perform in Java?
String caches its hashCode in a field, so the second and every later lookup of the same token skips rehashing entirely -- exactly the opposite of Go's map, and it makes a hot vocabulary nearly free. Strings whose chars all fit Latin-1 are stored one byte per char, halving an English vocabulary's footprint. The JIT needs a few thousand documents before the scoring loop leaves the interpreter, so a 500-document benchmark measures nothing. Escape analysis can stack-allocate the small posting only while it never leaves the method; putting it in the map defeats that. Time complexity is O(n log n) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialStudying for this? Student discounts on developer tools are collected on Noizz, tool by tool.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.