Reputation: 5723
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:
IndexWriter
and populates it with Document
s. IndexReader
: IndexReader reader = DirectoryReader.open(FSDirectory.open(new File(indexLocation)));
IndexSearcher
: IndexSearcher searcher = new IndexSearcher(reader);
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
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
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