java - Lucene:升级旧项目

标签 java class 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);
    }

}

我遇到的问题是:

  1. The method open(Path) in the type FSDirectory is not applicable for the arguments (File)

  2. 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/

相关文章:

python - Python 2.7 中的旧式和新式类

java - 子类不继承所有方法

Java 类/文件名驱动程序

java - JAR 文件找不到嵌入资源——相对路径有问题吗?

java RMI无法运行服务器

java - Lucene:根据相关性进行搜索和检索

java - Google App Engine (Java) 上的全文搜索

Java 程序使用或覆盖已弃用的 API?

java - Android Maven 无法解析配置的依赖关系

java - 使用 Java 格式化 XML 数据