Sorting with Lucene
Join the DZone community and get the full member experience.Join For Free
i talked about the lucene formula and how it calculate things using tf-idf for best matches. now i want to talk about the actual sorting implementation. as it turned out, the default sorting (by relevancy) is really simple. all you need is to get the relevant score for a query, then you shove the results through a heap with a specified size. the heap will take care of maintain the top results.
so far, that is pretty simple to understand. but the question is, how do you do sorting on a field value? the answer is, not easily.
getstringindex() does something very interesting. i returns a string index, which gives us:
- a string array containing all the distinct (sorted) value for this index.
- a int array with all the documents in the index, with the position of the value of that field in the string value array
now we can compare fields by their field position on the field, which give us pretty good sorting. unfortunately, this also require us to load all the values to memory. let us see another example, which would probably be easier to follow:
sorting by an integer is done like this:
get an array (whose size match the number of documents), we can then sort things easily because accessing the relevant field value only require us to have the document id to index into the array.
the reason lucene does this is that it uses an inverted index, and it has no easy way of going from the field values to the list documents it has. so it is easier to read all the values into memory and work with them there. i don’t like it, but off hand, i can’t think of a better way to handle this.
Published at DZone with permission of Oren Eini, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.