Saturday, March 3, 2007

Using Lucene FilteredQuery

The FAQ of Lucene just drops in the keyworld FilteredQuery, but at a first glance it doesn't seem to be such a straightforward thing to do.

Now, the problem at hand was to search in subscribed fora of a discussion system, thus only revealing stuff the user is able to see and that he is most likely nterested in. So lets say a user is subscribed to the Lobby (LBY) and the Humor (HUM) fora. When he specifies a search query for an entry that is about a policeman, we would like to achieve something like:

policeman AND forum:(LBY OR HUM)

But not quite. Actually we would like this to be a little bit more intelligent. So let's construct a FilteredQuery.

//1. Base query construction (parsing; queries static for the example)
Query uquery = queryParser.parse("policeman");
Query fquery = queryParser.parse("forum:(LBY OR HUM)");

//2. QueryFilter and FilterQuery construction
QueryFilter qf = new QueryFilter(fquery); //the query filter we want
FilteredQuery fq = new FilteredQuery(uquery, qf); //the filtered query

//3. Search
indexSearcher.search(fq);


That's all there is to it actually. Logically it becomes more interesting when your filters don't change too much, because then the caching capabilities kick in to deliver a good query performance.

Let's hope the user will find that one good joke about the policeman he was looking for ;)

0 comments: