使用 Lucene,我可以弄清楚如何创建文档、将值放入相关字段中,然后继续使用搜索器在索引文档中搜索匹配项。
但是,我现在更关心每个文档的特定字段中的匹配数。只要知道存在匹配就可以了,但我想知道在该字段中找到该模式的次数。
示例。
Document doc = new Document();
doc.add(new Field("TNAME", "table_one", Field.Store.YES, Field.Index.NOT_ANALYZED));
doc.add(new Field("CNAME", "column_one", Field.Store.YES, Field.Index.NOT_ANALYZED));
doc.add(new Field("DATA", "This would be the data found in this particular field of a single document", Field.Store.NO, Field.Index.ANALYZED));
如果我想执行文档搜索,查询“DATA”字段以计算出满足 ^d.* 模式的次数,我该怎么做? (给出上述文档的结果2)。
最佳答案
找到简单答案:
IndexSearcher searcher = new IndexSearcher(directory);
IndexReader reader = searcher.getIndexReader();
RegexTermEnum regexTermEnum = new RegexTermEnum(reader, new Term(
"field", "d.*"), new JavaUtilRegexCapabilities());
do {
System.out.println("Next:");
System.out.println("\tDoc Freq: " + regexTermEnum.docFreq());
if (regexTermEnum.term() != null) {
System.out.println("\t"+regexTermEnum.term());
TermDocs td = reader.termDocs(regexTermEnum.term());
while(td.next()){
System.out.println("Found "+ td.freq()+" matches in document " + reader.document(td.doc()).get("name"));
}
}
} while (regexTermEnum.next());
System.out.println("End.");
关于java - 计算文档字段中正则表达式查询匹配的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2059631/