Book Image

Lucene 4 Cookbook

By : Edwood Ng, Vineeth Mohan
Book Image

Lucene 4 Cookbook

By: Edwood Ng, Vineeth Mohan

Overview of this book

Table of Contents (16 chapters)
Lucene 4 Cookbook
About the Authors
About the Reviewers

Sorting with custom FieldComparator

Besides building your own Collector to customize how the results are stored and sorted, another way to customize results sorting is to implement your own FieldComparator for SortField. Note that this customization only deals with the sorting aspect of the result set; it does not give you the flexibility to filter out results, as you would have with Collector.

To implement a FieldComparator, we need to implement two classes: FieldComparator and FieldComparatorSource. The FieldComparator is the underlying class that contains the methods for comparing the documents in the result set. The FieldComparatorSource is a class that instantiates FieldComparator. It acts like a wrapper on FieldComparator. To use it, we pass our own FieldComparatorSource in the place of SortField.Type into the constructor of Sor tField.

How to do it...

Let's take a look at how FieldComparator is implemented. We will build a custom FieldComparator to sort results on a single-valued field...