【问题标题】:Lucene: upgrade old projectLucene:升级旧项目
【发布时间】:2018-06-08 21:52:35
【问题描述】:

我很久以前就使用 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) 不适用于 参数(文件)

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

我该如何解决这个问题?

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

【问题讨论】:

    标签: java class lucene


    【解决方案1】:

    1 - 使用File.toPath进行转换:

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

    2 - 使用DirectoryReader.open:

    DirectoryReader indexreader = DirectoryReader.open(directory);
    

    【讨论】:

      猜你喜欢
      • 2018-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-03
      • 2022-12-07
      • 1970-01-01
      • 2018-11-04
      • 2015-07-29
      相关资源
      最近更新 更多