Eypros
Eypros

Reputation: 5723

Searching lucene Index more than once returns zero result

Well, I am trying to start with lucene and I am using this example here which is a console example. I run it through eclipse but everything seems to work smoothly until I conduct a second search.

The program briefly does the following:

  1. Uses an IndexWriter and populates it with Documents.
  2. Creates a IndexReader: IndexReader reader = DirectoryReader.open(FSDirectory.open(new File(indexLocation)));
  3. Creates an IndexSearcher: IndexSearcher searcher = new IndexSearcher(reader);
  4. Creates a TopScoreDocCollector: TopScoreDocCollector collector = TopScoreDocCollector.create(5, true);

I am mentioning these because I am not familiar with lucene and I am trying to narrow down the problem.

Then there is a loop where a query (String) is read by the console and the following commands are executed:

Query q = new QueryParser(Version.LUCENE_48, "contents", analyzer).parse(s);
searcher.search(q, collector);
ScoreDoc[] hits = collector.topDocs().scoreDocs;

Everything works smoothly as I mentioned before in the first loop. After that there is no result returned (hits is empty).

My question is whether I should reset/clean the searcher or something. Query q seems to acquire the correct query in the next times also so I don't think the problem to be here.

Upvotes: 0

Views: 355

Answers (2)

femtoRgon
femtoRgon

Reputation: 33351

You are right, reusing the Collector in that way was causing issues. The explanation is simply that Collector is stateful, and not designed for reuse.

Really there is no need to use Collector here at all. It's considered an 'Expert' API, and is entirely unnecessary here. It's a bit puzzling that the author of that example used it. Just change:

Query q = new QueryParser(Version.LUCENE_40, "contents", analyzer).parse(s);
searcher.search(q, collector);
ScoreDoc[] hits = collector.topDocs().scoreDocs;

To:

Query q = new QueryParser(Version.LUCENE_40, "contents", analyzer).parse(s);
TopDocs docs = searcher.search(q, 5);
ScoreDoc[] hits = docs.scoreDocs;

Also, doesn't look like the IndexReader is ever closed there. Might be a good idea to add that.

Upvotes: 2

Eypros
Eypros

Reputation: 5723

After some trial and error research I find out that the I had to create a new Collector for each query to work.

I just added collector = TopScoreDocCollector.create(5, true); inside the loop and it worked.

I don't know why though. If someone has an explanation for this it is welcome to share it.

Upvotes: 1

Related Questions