Lucene7.4.0中无法找到TermFreqVector和TermPositionVector接口如何解决
问题原因
你使用的Lucene 7.4.0版本已完全移除了TermFreqVector和TermPositionVector接口,这两个接口早在Lucene 4.x版本就被官方废弃,后续版本直接删除了相关定义。你参考的教程是针对Lucene 3.x及更早版本编写的,和当前使用的版本不兼容,因此IDE无法找到对应类。
解决方案
使用新版本Lucene提供的Terms、TermsEnum、PostingsEnum这套API即可实现相同的词向量读取功能,你现有的FieldType存储配置不需要改动,仅需替换读取词向量的业务代码即可。
替换后的代码示例
将报错的for循环内代码修改为如下写法:
for (ScoreDoc scoreDoc : results.scoreDocs) { // 直接复用之前已经打开的reader,不需要重复打开DirectoryReader Terms terms = reader.getTermVector(scoreDoc.doc, "tags"); if (terms == null) { continue; } // 遍历词项获取词频、位置、偏移等信息 TermsEnum termsEnum = terms.iterator(); BytesRef term; while ((term = termsEnum.next()) != null) { String termText = term.utf8ToString(); long termFreq = termsEnum.totalTermFreq(); // 加载位置和偏移信息 PostingsEnum postingsEnum = termsEnum.postings(null, PostingsEnum.POSITIONS | PostingsEnum.OFFSETS); postingsEnum.nextDoc(); int posCount = postingsEnum.freq(); for (int i = 0; i < posCount; i++) { int position = postingsEnum.nextPosition(); int startOffset = postingsEnum.startOffset(); int endOffset = postingsEnum.endOffset(); // 此处写入你的业务逻辑,比如查找"the"对应的位置索引 if ("the".equals(termText)) { int index = position; // 后续业务逻辑 } } } }
补充优化建议
你的pom.xml中存在JDK编译版本冲突问题,同时配置了1.5、1.6、1.8三个版本,建议统一为1.8避免编译异常:
- 修改properties节点下的编译器版本配置:
<properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> <java.version>1.8</java.version> <lucene.version>7.4.0</lucene.version> </properties>
- 删除
maven-jar-plugin配置节点内的<source>1.5</source>和<target>1.5</target>两行配置即可。
内容的提问来源于stack exchange,提问作者Even
相关产品推荐
相关产品推荐

