【问题标题】:How to get Document ids for Document Term Vector in Lucene如何在 Lucene 中获取文档术语向量的文档 ID
【发布时间】:2012-02-14 20:58:24
【问题描述】:

我是 Lucene 世界的新手,对该主题没有太多的工作知识。我需要提取文档术语向量,我在网上找到了以下代码How to extract Document Term Vector in Lucene 3.5.0

 /**
 * Sums the term frequency vector of each document into a single term frequency map
 * @param indexReader the index reader, the document numbers are specific to this reader
 * @param docNumbers document numbers to retrieve frequency vectors from
 * @param fieldNames field names to retrieve frequency vectors from
 * @param stopWords terms to ignore
 * @return a map of each term to its frequency
 * @throws IOException
 */
private Map<String,Integer> getTermFrequencyMap(IndexReader indexReader, List<Integer> docNumbers, String[] fieldNames, Set<String> stopWords)
throws IOException {
    Map<String,Integer> totalTfv = new HashMap<String,Integer>(1024);

    for (Integer docNum : docNumbers) {
        for (String fieldName : fieldNames) {
            TermFreqVector tfv = indexReader.getTermFreqVector(docNum, fieldName);
            if (tfv == null) {
                // ignore empty fields
                continue;
            }

            String terms[] = tfv.getTerms();
            int termCount = terms.length;
            int freqs[] = tfv.getTermFrequencies();

            for (int t=0; t < termCount; t++) {
                String term = terms[t];
                int freq = freqs[t];

                // filter out single-letter words and stop words
                if (StringUtils.length(term) < 2 ||
                    stopWords.contains(term)) {
                    continue; // stop
                }

                Integer totalFreq = totalTfv.get(term);
                totalFreq = (totalFreq == null) ? freq : freq + totalFreq;
                totalTfv.put(term, totalFreq);
            }
        }
    }

    return totalTfv;
}

我已经创建了位于以下目录中的索引。

String indexDir = "C:\\Lucene\\Output\\";
Directory dir = FSDirectory.open(new File(indexDir));
IndexReader reader = IndexReader.open(dir);

我的问题是我不知道如何获取上述功能所需的文档 ID(列出文档编号)。我尝试了几种方法,例如

TermDocs docs = reader.termDocs();

但它不起作用。

【问题讨论】:

  • 顺便说一句,你怎么知道什么是词频向量,却对 lucene 文档 id 一无所知?
  • @milan 我读到 Lucene 会自动执行此操作,但上面的代码有点混乱,因为“docNumbers”是作为参数传递的。

标签: lucene


【解决方案1】:

Lucene 从零开始分配 id,maxDoc() 是上限,因此您可以简单地循环获取所有 id,跳过已删除的文档(Lucene 在调用 deleteDocument 时将它们标记为删除):

for (int docNum=0; docNum < reader.maxDoc(); docNum++) {
    if (reader.isDeleted(docNum)) {
        continue;
    }
    TermFreqVector tfv = reader.getTermFreqVector(docNum, "fieldName");
    ...
}

为此,您必须在索引期间启用它们,请参阅Field.TermVector

【讨论】:

  • 感谢您的回复 我已经尝试过了,但还是不行。事实上,问题出在创建索引时的以下行; doc.add(new Field("contents", new FileReader(f)); 我已将其替换为以下行并且它有效; doc.add(new Field("contents" , new FileReader(f),Field.TermVector.YES));
猜你喜欢
  • 1970-01-01
  • 2012-02-05
  • 2016-06-18
  • 2010-11-20
  • 1970-01-01
  • 2018-04-29
  • 2011-03-19
  • 2012-02-22
  • 1970-01-01
相关资源
最近更新 更多