Lucene’s high-level search API parallelizes search automatically, achieving superb performance.
The low-level expert API does not do that. Here is a solution to parallelize custom search. It is Open Source.
Introduction
The Open Source search engine Lucene has evolved into a very smart and efficient search tool. It offers both high level search interfaces as well as low-level (expert) interfaces. If you pass it an Executor, the high-level interface (API) automatically enables all the CPU’s in a server to work on your queries as fast as possible. The results are downright fantastic. For quite large data sets and quite complicated queries, you will get results in milliseconds.
Concurrency and the expert interface
However, the low-level API does not put all your cores to work automatically. That means that as soon as queries become more complicated and you have to use the low-level API, it runs slower. That is not a problem as long as you limit the number of documents to, say, 10,000,000. Most functionality like sorting and facets still runs in a few 100 of milliseconds. But when you have many more documents and when you must support many concurrent queries, the help of more CPU’s would be very nice.
Before I introduce our solution, a quick word about the so-called expert API and the problem with it.
How the low-level API works: Collector
The main work of any search engine consists of intersecting, intersecting and yet more intersecting. Lucene’s low-level expert API gives a programmer access to the inner loop that performs the intersecting. Lucene has a hook that, regardless of what intersection algorithm it uses (zip, gallop, bisect, skip lists, and so on, look for “integer intersection algorithms”), it calls your code as soon as it determines a document is in the set defined by your query.
The hook consists of an interface called Collector, that has a method collect(). When you pass an object that supports this interface, Lucene will call collect() for each result. This method must be very short, small and fast, since Lucene will call it many, many times.
The problem is that the search methods that accept a Collector do not enable threads and leave all but one of your CPU’s idle. There is a good reason for that.
The problem with Collectors
The Collector interface is inherently thread-unsafe. The reason for this is the way the setNextReader() method on Collector works. Internally, Lucene maintains an index composed of tens of segments each containing a subset of the complete index. During search, Lucene tells the collector that a new segment starts and that the following calls to collect() are in the context of this segment. All but the most trivial Collectors need to remember this context and this is why the Collector is unsuitable for multi-threading. What if two threads call setNextReader() with different arguments?
Using Lucene’s internal segmenting to divide the work is quite natural. Indeed, the high-level API divides the work based on segments. What if custom Collectors could also use this?
SuperCollector and SubCollector
We designed two new interfaces that are much like the Collector, but just different enough to support multi-threaded search for any operation. The first is SuperCollector. It basically replaces Collector in the call to search(). So instead of (pseudocode):
searcher.search(query, filter, collector)
we use:
searcher.search(query, filter, supercollector)
That’s all.
The SuperCollector creates subCollectors that are thread-safe:
subcollector = supercollector.subCollector(...)
The new search() method calls the method subCollector() for as many threads it wants to create. SubCollector is almost identical to Collector. If fact, it is a subclass of Collector. It supports the setNextReader() and setScorer() methods and of course collect() and it adds only one more method:
subcollector.complete()
The thread executing the search calls complete() after it is finished. Some collectors do most of their work during collect() calls, but others just collect data for post-processing later. Such collectors can put time-consuming post-processing in the complete() method so that it executes in parallel as well.
Encapsulating existing code
The nasty thing about the Collector API is that once you start using it, the simple parts of your query, that used to be automatically parallelized by Lucene, will now be single-threaded as well. Therefore we also need to create Super/SubCollectors for simple queries.
Simple queries are queries with results sorted on score or on a field value. The parallelization is spread across the Lucene code. We found it and encapsulated it as follows:
- Some code in the search method at lines 450-456 and lines 535-547 creates the threads. We replace this code with one generic piece in search().
- Code for creating the TopFieldCollector at line 535 for sorting on a field while the case for sorting on score is degelated to SearcherCallableNoSort which will delegate further until a TopScoreDocCollector is finally created at line 490. We encapsulate this in specific subCollector() methods.
- Code for merging the results at lines 460-471 (sort on score) and at lines 550-559 (sort on field). We encapsulate this in SuperCollector.
Example: TopFieldSuperCollector
Here are the results for applying the encapsulation outlined above to the way Lucene’s default TopFieldCollector works. These are the important steps:
First, the TopDocsSuperCollector creates the proper SubCollector when search() asks for it:
TopFieldSubCollector createSubCollector() { return new TopFieldSubCollector(...); }
The search continues as normal. Lucene calls collect() for each result found, but this happens in a thread. The TopFieldSubCollector simply delegates to a standard Lucene TopFieldCollector.
The search signals completion of the segment by calling complete(), which simply delegates again:
void complete() { this.topdocs = this.delegate.topDocs() }
Finally, the merge happens when the application asks for the result by calling topDocs():
TopDocs topDocs(int start) {
for (TopFieldSubCollector sub : super.subs) {
// merge results from subcollectors
}
return topDocs
}
What next?
The concept above has been implemented for simple search and shows very much speed-up. We now have to create Super- and SubCollectors for the other functions we use:
- for sorting by relevance: TopDocsCollector
- for calculating facets: FacetCollector
- for creating trees of collectors: MultiCollector
- for de-duplicating results: DeDupCollector
- for query-time join: KeyCollector and ScoreCollector
For each of them we are working out the design and then we will add them. I will post the results when we are done.
Meanwhile, you can follow the code here: Meresco Lucene.