2011-08-13 41 views
0

我想用Lucene使用正则表达式来查找“Bug报告”,但每当我尝试它时都不起作用。使用Lucene查找正则表达式匹配?

我使用了Lucene page中的代码来避免错误的设置。

这里是我的代码:

import java.util.regex.Pattern; 

import org.apache.lucene.analysis.SimpleAnalyzer; 
import org.apache.lucene.document.Document; 
import org.apache.lucene.document.Field; 
import org.apache.lucene.index.IndexWriter; 
import org.apache.lucene.index.Term; 
import org.apache.lucene.search.IndexSearcher; 
import org.apache.lucene.search.regex.JakartaRegexpCapabilities; 
import org.apache.lucene.search.regex.RegexCapabilities; 
import org.apache.lucene.search.regex.RegexQuery; 
import org.apache.lucene.store.RAMDirectory; 

public class Rege { 

    private static IndexSearcher searcher; 
    private static final String FN = "field"; 

    public static void main(String[] args) throws Exception { 
    RAMDirectory directory = new RAMDirectory(); 
    try { 

     IndexWriter writer = new IndexWriter(directory, 
      new SimpleAnalyzer(), true, 
      IndexWriter.MaxFieldLength.LIMITED); 
     Document doc = new Document(); 
     doc 
      .add(new Field(
       FN, 
       "[Phpmyadmin-devel] Commits against bug 601721 (Cookie auth mode faulty with IIS)", 
       Field.Store.NO, Field.Index.ANALYZED)); 
     writer.addDocument(doc); 
     writer.optimize(); 
     writer.close(); 
     searcher = new IndexSearcher(directory, true); 

    } catch (Exception e) { 
     e.printStackTrace(); 
    } 

    System.err.println(regexQueryNrHits("bug [0-9]+",null)); 

    } 

    private static Term newTerm(String value) { 
    return new Term(FN, value); 
    } 

    private static int regexQueryNrHits(String regex, 
     RegexCapabilities capability) throws Exception { 

    RegexQuery query = new RegexQuery(newTerm(regex)); 

    if (capability != null) 
     query.setRegexImplementation(capability); 

    return searcher.search(query, null, 1000).totalHits; 
    } 

} 

我希望bug [0-9]+返回1但事实并非如此。我也用Java测试了正则表达式,它工作。

回答

0

如果您的字段索引为“字符串”类型(而不是“文本”类型),则您的正则表达式必须匹配整个字段值。
试试这个,这需要你的正则表达式给外地的两端:

System.err.println(regexQueryNrHits("^.*bug [0-9]+.*$",null)); 
0

谢谢,但仅此并没有解决问题。问题是Field.Index.ANALYZED标志:

看来,lucene并没有以适当的方式索引数字,以便正则表达式可以与他们一起使用。

我改变:

doc.add(new Field(
FN,"[Phpmyadmin-devel] Commits against bug 601721 (Cookie auth mode faulty with IIS)",Field.Store.NO, Field.Index.ANALYZED)); 

doc.add(new Field(
FN,"[Phpmyadmin-devel] Commits against bug 601721 (Cookie auth mode faulty with IIS)",Field.Store.NO, Field.Index.NOT_ANALYZED)); 

,并与改进的正则表达式:

System.err.println(regexQueryNrHits("^.*bug #+[0-9]+.*$", 
new JavaUtilRegexCapabilities())); 

它终于成功了! :)

+0

问题不在于数字。问题在于如何使用正则表达式查询和分析来协同工作。你的正则表达式必须匹配* term *,而不是整个字段。这就是为什么它与NOT_ANALYZED一起工作的原因,你已经把整个领域变成了一个单一的术语。但有一个警告。当你创建一个未经分析的领域时,你放弃了使用搜索索引的大部分优势(例如性能)。 – femtoRgon