如何在Lucene中使用tfidf相似度对文档进行排名

如何在Lucene中使用tfidf相似度对文档进行排名

本文介绍了如何在Lucene中使用tfidf相似度对文档进行排名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在创建索引和搜索查询的基本代码中,我想使用TFIDF相似性对检索到的文档进行排名.但是我收到一个错误无法实例化类型TFIDFSimilarity".我的代码如下:

In a basic code to create index and search queries, I want to use TFIDFsimilarity to rank retrieved documents. But I am getting an error "Cannot instantiate the type TFIDFSimilarity". My code is given below:

public class TFIDF_T {

private static Document createDocument(String id, String tb) {
    Document doc = new Document();
    doc.add(new Field("id", id, TextField.TYPE_STORED));
    doc.add(new Field("tb", tb, TextField.TYPE_STORED));
    return doc;
}

private static void search(IndexSearcher searcher, String queryString, Analyzer analyzer) throws IOException, ParseException {
    QueryParser parser = new QueryParser("tb", analyzer);
    Query query = parser.parse(queryString);
    ScoreDoc[] hits = searcher.search(query, 20).scoreDocs;
    int hitCount = hits.length;
    for (int i = 0; i < hitCount; i++) {
        Document doc = searcher.doc(hits[i].doc);
        System.out.println(doc.get("id"));
    }
}

public static void run(String path) throws IOException, ParseException {
    int ctr = 0;
    Analyzer analyzer = new StandardAnalyzer();
    RAMDirectory directory = new RAMDirectory();
    IndexWriterConfig config = new IndexWriterConfig(analyzer);
    IndexWriter iwriter = new IndexWriter(directory, config);
        String id = "101";
        String tb = "How to rank documents using tfidfsimilairty";
        iwriter.addDocument(createDocument(id, tb));
    }
    iwriter.close();
    DirectoryReader ireader = DirectoryReader.open(directory);
    IndexSearcher isearcher = new IndexSearcher(ireader);
    isearcher.setSimilarity(new **TFIDFSimilarity**());
    String tb1 = "How to rank documents using tfidfsimilairty";
    search(isearcher, tb1, analyzer);
    }
    ireader.close();
    directory.close();
  }
}

推荐答案

TFIDFSimilarity 是一个抽象类.您无法实例化它.

TFIDFSimilarity is an abstract class. You can't instantiate it.

ClassicSimilarity 是它的一个实现(假设您使用的是 5.4 或更高版本,否则 DefaultSimilarity).改用它.

ClassicSimilarity is an implementation of it (Assuming you are using 5.4 or later, otherwise DefaultSimilarity). Use that instead.

这篇关于如何在Lucene中使用tfidf相似度对文档进行排名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 12:06