2011-08-13 39 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