Add Searcher class

This commit is contained in:
coolneng 2021-01-11 20:59:56 +01:00
parent 7dff28d7d0
commit cea856ab60
Signed by: coolneng
GPG Key ID: 9893DA236405AF57
2 changed files with 63 additions and 0 deletions

View File

@ -29,6 +29,11 @@
<artifactId>lucene-analyzers-common</artifactId> <artifactId>lucene-analyzers-common</artifactId>
<version>8.6.3</version> <version>8.6.3</version>
</dependency> </dependency>
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-queryparser</artifactId>
<version>8.6.3</version>
</dependency>
<dependency> <dependency>
<groupId>com.google.code.gson</groupId> <groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId> <artifactId>gson</artifactId>

View File

@ -0,0 +1,58 @@
package org.RI.P2;
import java.io.IOException;
import java.nio.file.Paths;
import java.text.ParseException;
import org.apache.lucene.analysis.core.WhitespaceAnalyzer;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.queryparser.classic.QueryParser;
public class Searcher {
IndexReader index;
String dataPath;
String indexPath;
Searcher(String dataPath, String indexPath) {
this.dataPath = dataPath;
this.indexPath = indexPath;
}
IndexSearcher createIndexSearcher() throws IOException {
Directory indexDirectory = FSDirectory.open(Paths.get(indexPath));
IndexReader indexReader = DirectoryReader.open(indexDirectory);
IndexSearcher searcher = new IndexSearcher(indexReader);
return searcher;
}
TopDocs searchFiles(String queryString, int resultNumber)
throws IOException, org.apache.lucene.queryparser.classic.ParseException {
IndexSearcher searcher = createIndexSearcher();
Query query = new QueryParser("abstract", new WhitespaceAnalyzer()).parse(queryString);
TopDocs topDocs = searcher.search(query, resultNumber);
return topDocs;
}
private static void usage() {
System.out.println("Usage: Searcher <directory>");
System.exit(1);
}
public static void main(String[] args) throws IOException, ParseException {
if (args.length != 1) {
usage();
}
String dataDirectory = args[0];
String indexDirectory = ".index";
Indexer indexer = new Indexer(dataDirectory, indexDirectory);
indexer.populateIndex();
Searcher searcher = new Searcher(dataDirectory, indexDirectory);
}
}