我很久以前就使用 Lucene 4.6 构建了一个项目。现在目前想升级到7.3。
该项目有三个文件,每个文件一个类(与文件同名):Main、Indexer、Search。
Main 类承载逻辑并以过程方式调用 Indexer 和 Search。
我在搜索时遇到问题。
在Main.java内部,我定义了数据目录的位置以及索引的位置,并给出搜索词:
File dataDirectory = new File("C:\\datalocation");
File indexDirectory = new File("C:\\indexlocation");
(...)
Search.searchThis(indexDirectory,"Maven");
Search.java 内部:
package code;
import java.io.File;
import java.io.IOException;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
public class Search {
static void searchThis(File indexDirectory, String findme)
throws IOException, ParseException {
Directory directory = FSDirectory.open(indexDirectory);
@SuppressWarnings("deprecation")
IndexReader indexreader = IndexReader.open(directory);
IndexSearcher searcher = new IndexSearcher(indexreader);
QueryParser parser = new QueryParser("contents",
new StandardAnalyzer());
Query query = parser.parse(findme);
TopDocs topDocs = searcher.search(query, 10);
ScoreDoc[] hits = topDocs.scoreDocs;
for (int i = 0; i < hits.length; i++) {
int docId = hits[i].doc;
Document d = searcher.doc(docId);
System.out.println(d.get("path"));
}
System.out.println("Found: " + topDocs.totalHits);
}
}
我遇到的问题是:
-
The method open(Path) in the type FSDirectory is not applicable for the arguments (File)
-
The method open(Directory) is undefined for the type IndexReader
如何解决这个问题?
将“indexDirectory”类型更改为“Path”不是一个值得考虑的选项。
最佳答案
1 - 使用 File.toPath 进行转换:
File yourFile = indexDirectory;
Path yourPath = yourFile.toPath();
Directory directory = FSDirectory.open(yourPath);
2 - 使用DirectoryReader.open :
DirectoryReader indexreader = DirectoryReader.open(directory);
关于java - Lucene:升级旧项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50768847/