首页 > 解决方案 > 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. FSDirectory 类型中的方法 open(Path) 不适用于参数 (File)

  2. 未为 IndexReader 类型定义方法 open(Directory)

我怎样才能解决这个问题?

不考虑将“indexDirectory”类型更改为“路径”。

标签: javaclasslucene

解决方案


1 - 使用File.toPath转换:

File yourFile = indexDirectory;
Path yourPath = yourFile.toPath();
Directory directory = FSDirectory.open(yourPath);

2 - 使用DirectoryReader.open

DirectoryReader indexreader = DirectoryReader.open(directory);

推荐阅读