3

我是 Java 和 Lucene 的新手。我正在尝试一个简单的 MLT 测试,但我没有得到任何结果。

import java.io.File;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.store.Directory;
import org.apache.lucene.util.Version;
import org.apache.lucene.index.DirectoryReader;
import java.io.IOException;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.queries.mlt.MoreLikeThis;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.SimpleFSDirectory;

public class HelloLucene {
  public static void main(String[] args) throws IOException, ParseException {
    StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_40);

    String indexPath = "C:/Users/Name/Desktop/Lucene";
    Directory index = new SimpleFSDirectory(new File(indexPath)); 

    IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_40, analyzer);

    IndexWriter w = new IndexWriter(index, config);
    addDoc(w, "Lucene in Action", "193398817");
    addDoc(w, "Lucene for Dummies", "55320055Z");
    addDoc(w, "Managing Gigabytes", "55063554A");
    addDoc(w, "The Art of Computer Science", "9900333X");
    w.close();  

    IndexReader reader = DirectoryReader.open(index);
    System.out.println("Reader has " + reader.numDocs() + " docs on it.");

    MoreLikeThis mlt = new MoreLikeThis(reader);
    mlt.setMinTermFreq(1);
    mlt.setMinDocFreq(1);
    Query query = mlt.like(0); //doc ID

    IndexSearcher searcher = new IndexSearcher(reader);    
    TopDocs topDocs = searcher.search(query,5);

    System.out.println("Found " + topDocs.totalHits + " hits.");

    for (ScoreDoc scoreDoc : topDocs.scoreDocs) {
        Document doc = searcher.doc(scoreDoc.doc);
        System.out.println(scoreDoc.doc + ". " + doc.get("isbn") + "\t" + doc.get("title"));
    }    

    reader.close();

  }

  private static void addDoc(IndexWriter w, String title, String isbn) throws IOException {
    Document doc = new Document();
    doc.add(new TextField("title", title, Field.Store.YES));

    // use a string field for isbn because we don't want it tokenized
    doc.add(new StringField("isbn", isbn, Field.Store.YES));
    w.addDocument(doc);
  }
}

这就是我得到的:

阅读器上有 4 个文档。
找到 0 次点击。

我尝试使用 Luke 来检查 Doc 的 ID,显然没有任何问题。
我什至在那里做了一些测试,我不知道出了什么问题:(
在网上做了很多搜索,有人说了一些关于 MinTermFreq 和 MinDocFreq 的设置,我尝试了 1 和 0,但什么也没得到。

有人有想法吗?
提前致谢!

[已解决] 编辑:

它现在工作!
我只需要添加这个:

mlt.setAnalyzer(analyzer);
mlt.setFieldNames(new String[] {"title"});
4

1 回答 1

0

它现在工作!我只需要添加这个:

mlt.setAnalyzer(分析器);mlt.setFieldNames(new String[] {"title"});

于 2014-02-17T01:36:39.243 回答