java - Lucene:升级旧项目
问题描述
我很久以前就使用 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);
}
}
我遇到的问题是:
FSDirectory 类型中的方法 open(Path) 不适用于参数 (File)
未为 IndexReader 类型定义方法 open(Directory)
我怎样才能解决这个问题?
不考虑将“indexDirectory”类型更改为“路径”。
解决方案
1 - 使用File.toPath转换:
File yourFile = indexDirectory;
Path yourPath = yourFile.toPath();
Directory directory = FSDirectory.open(yourPath);
2 - 使用DirectoryReader.open:
DirectoryReader indexreader = DirectoryReader.open(directory);
推荐阅读
- python - Python 简介 - 数字系列
- angular - 使用 Angular2 显示树视图
- git - 远程存储库上的 SSH 密钥。(Github 或 Bitbucket)
- java - @Transactional 循环回滚
- javascript - 找不到可靠的赔率解决方案
- javascript - 正则表达式 - RxJS 6 迁移管道
- python-3.x - 如何在python3中使用pickle序列化对象
- vb.net - 即使文件不可用,从文件路径获取默认图标
- ruby - 在没有 require_relative 的情况下测试我的 ruby 模块本地更改
- java - Java JCache 字符串键与复合键