Lucene教程



1 lucene簡介
1.1 什麼是lucene
    Lucene是一個全文搜索框架,而不是應用產品。因此它並不像www.baidu.com 或者google Desktop那麼拿來就能用,它只是提供了一種工具讓你能實現這些產品。
2 lucene的工作方式
    lucene提供的服務實際包含兩部分:一入一出。所謂入是寫入,即將你提供的源(本質是字符串)寫入索引或者將其從索引中刪除;所謂出是讀出,即向用戶提供全文搜索服務,讓用戶可以通過關鍵詞定位源。
2.1寫入流程
    源字符串首先經過analyzer處理,包括:分詞,分成一個個單詞;去除stopword(可選)。
將源中需要的信息加入Document的各個Field中,並把需要索引的Field索引起來,把需要存儲的Field存儲起來。
    將索引寫入存儲器,存儲器可以是內存或磁盤。
2.2讀出流程
    用戶提供搜索關鍵詞,經過analyzer處理。
對處理後的關鍵詞搜索索引找出對應的Document。
用戶根據需要從找到的Document中提取需要的Field。
3 一些需要知道的概念
3.1 analyzer
    Analyzer是分析器,它的作用是把一個字符串按某種規則劃分成一個個詞語,並去除其中的無效詞語,這裏說的無效詞語是指英文中的“of”、“the”,中文中的“的”、“地”等詞語,這些詞語在文章中大量出現,但是本身不包含什麼關鍵信息,去掉有利於縮小索引文件、提高效率、提高命中率。
  分詞的規則千變萬化,但目的只有一個:按語義劃分。這點在英文中比較容易實現,因爲英文本身就是以單詞爲單位的,已經用空格分開;而中文則必須以某種方法將連成一片的句子劃分成一個個詞語。具體劃分方法下面再詳細介紹,這裏只需瞭解分析器的概念即可。
3.2 document
  用戶提供的源是一條條記錄,它們可以是文本文件、字符串或者數據庫表的一條記錄等等。一條記錄經過索引之後,就是以一個Document的形式存儲在索引文件中的。用戶進行搜索,也是以Document列表的形式返回。
3.3 field
    一個Document可以包含多個信息域,例如一篇文章可以包含“標題”、“正文”、“最後修改時間”等信息域,這些信息域就是通過Field在Document中存儲的。
    Field有兩個屬性可選:存儲和索引。通過存儲屬性你可以控制是否對這個Field進行存儲;通過索引屬性你可以控制是否對該Field進行索引。這看起來似乎有些廢話,事實上對這兩個屬性的正確組合很重要,下面舉例說明:還是以剛纔的文章爲例子,我們需要對標題和正文進行全文搜索,所以我們要把索引屬性設置爲真,同時我們希望能直接從搜索結果中提取文章標題,所以我們把標題域的存儲屬性設置爲真,但是由於正文域太大了,我們爲了縮小索引文件大小,將正文域的存儲屬性設置爲假,當需要時再直接讀取文件;我們只是希望能從搜索解果中提取最後修改時間,不需要對它進行搜索,所以我們把最後修改時間域的存儲屬性設置爲真,索引屬性設置爲假。上面的三個域涵蓋了兩個屬性的三種組合,還有一種全爲假的沒有用到,事實上Field不允許你那麼設置,因爲既不存儲又不索引的域是沒有意義的。
3.4 term
  term是搜索的最小單位,它表示文檔的一個詞語,term由兩部分組成:它表示的詞語和這個詞語所出現的field。
3.5 tocken
    tocken是term的一次出現,它包含trem文本和相應的起止偏移,以及一個類型字符串。一句話中可以出現多次相同的詞語,它們都用同一個term表示,但是用不同的tocken,每個tocken標記該詞語出現的地方。
3.6 segment
    添加索引時並不是每個document都馬上添加到同一個索引文件,它們首先被寫入到不同的小文件,然後再合併成一個大索引文件,這裏每個小文件都是一個segment。
4 如何建索引
4.1 最簡單的能完成索引的代碼片斷
IndexWriter writer = new IndexWriter(“/data/index/”, new StandardAnalyzer(), true);
Document doc = new Document();
doc.add(new Field("title", "lucene introduction", Field.Store.YES, Field.Index.TOKENIZED));
doc.add(new Field("content", "lucene works well", Field.Store.YES, Field.Index.TOKENIZED));
writer.addDocument(doc);
writer.optimize();
writer.close();
下面我們分析一下這段代碼。
首先我們創建了一個writer,並指定存放索引的目錄爲“/data/index”,使用的分析器爲StandardAnalyzer,第三個參數說明如果已經有索引文件在索引目錄下,我們將覆蓋它們。然後我們新建一個document。
  我們向document添加一個field,名字是“title”,內容是“lucene introduction”,對它進行存儲並索引。再添加一個名字是“content”的field,內容是“lucene works well”,也是存儲並索引。
然後我們將這個文檔添加到索引中,如果有多個文檔,可以重複上面的操作,創建document並添加。
添加完所有document,我們對索引進行優化,優化主要是將多個segment合併到一個,有利於提高索引速度。
   隨後將writer關閉,這點很重要。
   對,創建索引就這麼簡單!
  當然你可能修改上面的代碼獲得更具個性化的服務。
4.2 索引文本文件
    如果你想把純文本文件索引起來,而不想自己將它們讀入字符串創建field,你可以用下面的代碼創建field:
Field field = new Field("content", new FileReader(file));
    這裏的file就是該文本文件。該構造函數實際上是讀去文件內容,並對其進行索引,但不存儲。



Lucene 2 教程

Lucene是apache組織的一個用java實現全文搜索引擎的開源項目。 其功能非常的強大,api也很簡單。總得來說用Lucene來進行建立 和搜索和操作數據庫是差不多的(有點像),Document可以看作是 數據庫的一行記錄,Field可以看作是數據庫的字段。用lucene實 現搜索引擎就像用JDBC實現連接數據庫一樣簡單。

Lucene2.0,它與以前廣泛應用和介紹的Lucene 1.4.3並不兼容。 Lucene2.0的下載地址是http://apache.justdn.org/lucene/java/


例子一 :

1、在windows系統下的的C盤,建一個名叫s的文件夾,在該文件夾裏面隨便建三個txt文件,隨便起名啦,就叫"1.txt","2.txt"和"3.txt"啦 
其中1.txt的內容如下:

中華人民共和國   
全國人民   
2006年  

而"2.txt"和"3.txt"的內容也可以隨便寫幾寫,這裏懶寫,就複製一個和1.txt文件的內容一樣吧

2、下載lucene包,放在classpath路徑中 
建立索引:

package lighter.javaeye.com;   
  
import java.io.BufferedReader;   
import  java.io.File;   
import java.io.FileInputStream;   
import  java.io.IOException;   
import java.io.InputStreamReader;   
import  java.util.Date;   
  
import  org.apache.lucene.analysis.Analyzer;   
import org.apache.lucene.analysis.standard.StandardAnalyzer;   
import org.apache.lucene.document.Document;   
import org.apache.lucene.document.Field;   
import org.apache.lucene.index.IndexWriter;   
  
/** */ /**   
 * author lighter date 2006-8-7  
  */   
public   class TextFileIndexer  {   
    public   static   void  main(String[] args)  throws Exception  {   
        /**/ /*  指明要索引文件夾的位置,這裏是C盤的S文件夾下 */   
        File fileDir =   new  File( " c:\\s " );   
  
        /**/ /*  這裏放索引文件的位置  */   
        File indexDir =   new  File( " c:\\index " );   
        Analyzer luceneAnalyzer =   new  StandardAnalyzer();   
        IndexWriter indexWriter =   new  IndexWriter(indexDir, luceneAnalyzer,   
                true );   
        File[] textFiles =  fileDir.listFiles();   
        long  startTime  =   new Date().getTime();   
           
        // 增加document到索引去    
        for  ( int  i  =   0 ; i  < textFiles.length; i ++ )  {   
            if  (textFiles[i].isFile()   
                    &&  textFiles[i].getName().endsWith( " .txt " ))  {   
                System.out.println(" File  "   + textFiles[i].getCanonicalPath()   
                        +   " 正在被索引. " );   
                String temp =  FileReaderAll(textFiles[i].getCanonicalPath(),   
                        " GBK " );   
                System.out.println(temp);   
                Document document =   new  Document();   
                Field FieldPath =   new  Field( " path ", textFiles[i].getPath(),   
                        Field.Store.YES, Field.Index.NO);   
                Field FieldBody =   new  Field( " body ", temp, Field.Store.YES,   
                        Field.Index.TOKENIZED,   
                        Field.TermVector.WITH_POSITIONS_OFFSETS);   
                document.add(FieldPath);   
                document.add(FieldBody);   
                indexWriter.addDocument(document);   
            }   
        }   
        // optimize()方法是對索引進行優化    
        indexWriter.optimize();   
        indexWriter.close();   
           
        // 測試一下索引的時間    
        long  endTime  =   new  Date().getTime();   
        System.out   
                .println(" 這花費了"   
                        +  (endTime  -  startTime)   
                        +   "  毫秒來把文檔增加到索引裏面去! "   
                        +  fileDir.getPath());   
    }    
  
     public   static String FileReaderAll(String FileName, String charset)   
            throws  IOException  {   
        BufferedReader reader =   new  BufferedReader( new InputStreamReader(   
                new  FileInputStream(FileName), charset));   
        String line =   new  String();   
        String temp =   new  String();   
           
        while  ((line  =  reader.readLine())  !=   null)  {   
            temp +=  line;   
        }   
        reader.close();   
        return  temp;   
    }    
}  

索引的結果:

File C:\s\ 1 .txt正在被索引.   
中華人民共和國全國人民2006年   
File C:\s\ 2 .txt正在被索引.   
中華人民共和國全國人民2006年   
File C:\s\ 3 .txt正在被索引.   
中華人民共和國全國人民2006年   
這花費了297 毫秒來把文檔增加到索引裏面去 ! c:\s  


3、建立了索引之後,查詢啦....

package  lighter.javaeye.com;   
  
import java.io.IOException;   
  
import org.apache.lucene.analysis.Analyzer;   
import org.apache.lucene.analysis.standard.StandardAnalyzer;   
import  org.apache.lucene.queryParser.ParseException;   
import org.apache.lucene.queryParser.QueryParser;   
import org.apache.lucene.search.Hits;   
import org.apache.lucene.search.IndexSearcher;   
import org.apache.lucene.search.Query;   
  
public   class TestQuery  {   
    public   static   void  main(String[] args)  throws IOException, ParseException  {   
        Hits hits =   null ;   
        String queryString =   " 中華 ";   
        Query query =   null ;   
        IndexSearcher searcher =   new  IndexSearcher( " c:\\index " );   
  
        Analyzer analyzer =   new  StandardAnalyzer();   
        try   {   
            QueryParser qp =   new  QueryParser( " body ", analyzer);   
            query =  qp.parse(queryString);   
        }  catch  (ParseException e)  {   
        }   
        if  (searcher  !=   null )  {   
            hits =  searcher.search(query);   
            if  (hits.length()  >   0 )  {   
                System.out.println(" 找到: "  +  hits.length()  +   "  個結果! " );   
            }   
        }   
    }  
  
}   

其運行結果:

找到: 3  個結果!

 

Lucene 其實很簡單的,它最主要就是做兩件事:建立索引和進行搜索 
來看一些在lucene中使用的術語,這裏並不打算作詳細的介紹,只是點一下而已----因爲這一個世界有一種好東西,叫搜索。

IndexWriter:lucene中最重要的的類之一,它主要是用來將文檔加入索引,同時控制索引過程中的一些參數使用。

Analyzer:分析器,主要用於分析搜索引擎遇到的各種文本。常用的有StandardAnalyzer分析器,StopAnalyzer分析器,WhitespaceAnalyzer分析器等。

Directory:索引存放的位置;lucene提供了兩種索引存放的位置,一種是磁盤,一種是內存。一般情況將索引放在磁盤上;相應地lucene提供了FSDirectory和RAMDirectory兩個類。

Document:文檔;Document相當於一個要進行索引的單元,任何可以想要被索引的文件都必須轉化爲Document對象才能進行索引。

Field:字段。

IndexSearcher:是lucene中最基本的檢索工具,所有的檢索都會用到IndexSearcher工具;

Query:查詢,lucene中支持模糊查詢,語義查詢,短語查詢,組合查詢等等,如有TermQuery,BooleanQuery,RangeQuery,WildcardQuery等一些類。

QueryParser: 是一個解析用戶輸入的工具,可以通過掃描用戶輸入的字符串,生成Query對象。

Hits:在搜索完成之後,需要把搜索結果返回並顯示給用戶,只有這樣纔算是完成搜索的目的。在lucene中,搜索的結果的集合是用Hits類的實例來表示的。

上面作了一大堆名詞解釋,下面就看幾個簡單的實例吧: 
1、簡單的的StandardAnalyzer測試例子

 

package  lighter.javaeye.com;   
  
import java.io.IOException;   
import java.io.StringReader;   
  
import org.apache.lucene.analysis.Analyzer;   
import  org.apache.lucene.analysis.Token;   
import org.apache.lucene.analysis.TokenStream;   
import org.apache.lucene.analysis.standard.StandardAnalyzer;   
  
public   class StandardAnalyzerTest    
{   
     // 構造函數,    
     public StandardAnalyzerTest()   
    {   
    }    
     public   static  void  main(String[] args)    
    {   
        // 生成一個StandardAnalyzer對象    
        Analyzer aAnalyzer =   new  StandardAnalyzer();   
        // 測試字符串   
        StringReader sr =   new  StringReader( "lighter javaeye com is the are on ");   
        // 生成TokenStream對象    
        TokenStream ts =  aAnalyzer.tokenStream( " name ", sr);    
        try   {   
            int  i = 0 ;   
            Token t =  ts.next();   
            while (t != null )   
            {   
                // 輔助輸出時顯示行號   
                i++ ;   
                // 輸出處理後的字符   
                System.out.println(" 第 " + i + " 行: " + t.termText());   
                // 取得下一個字符   
                t= ts.next();   
            }   
        }  catch  (IOException e)  {   
            e.printStackTrace();   
        }   
    }    
}    

顯示結果:

第1行:lighter 
第2行:javaeye 
第3行:com

提示一下: 
StandardAnalyzer是lucene中內置的"標準分析器",可以做如下功能: 
1、對原有句子按照空格進行了分詞 
2、所有的大寫字母都可以能轉換爲小寫的字母 
3、可以去掉一些沒有用處的單詞,例如"is","the","are"等單詞,也刪除了所有的標點 
查看一下結果與"newStringReader("lighter javaeye com is the are on")"作一個比較就清楚明瞭。 
這裏不對其API進行解釋了,具體見lucene的官方文檔。需要注意一點,這裏的代碼使用的是lucene2的API,與1.43版有一些明顯的差別。

2、看另一個實例,簡單地建立索引,進行搜索

package lighter.javaeye.com;   
import org.apache.lucene.analysis.standard.StandardAnalyzer;   
import org.apache.lucene.document.Document;   
import org.apache.lucene.document.Field;   
import  org.apache.lucene.index.IndexWriter;   
import org.apache.lucene.queryParser.QueryParser;   
import org.apache.lucene.search.Hits;   
import org.apache.lucene.search.IndexSearcher;   
import org.apache.lucene.search.Query;   
import org.apache.lucene.store.FSDirectory;   
  
public   class FSDirectoryTest  {   
  
     // 建立索引的路徑    
     public   static  final  String path  =   " c:\\index2 ";   
  
    public   static   void  main(String[] args)  throws Exception  {   
        Document doc1 =   new  Document();   
        doc1.add( new  Field( " name " ,  "lighter javaeye com " ,Field.Store.YES,Field.Index.TOKENIZED));   
  
        Document doc2 =   new  Document();   
        doc2.add(new  Field( " name " ,  " lighter blog ",Field.Store.YES,Field.Index.TOKENIZED));   
  
        IndexWriter writer =   new  IndexWriter(FSDirectory.getDirectory(path,  true),  new  StandardAnalyzer(),  true );   
        writer.setMaxFieldLength(3 );   
        writer.addDocument(doc1);   
        writer.setMaxFieldLength(3 );   
        writer.addDocument(doc2);   
        writer.close();   
  
        IndexSearcher searcher =   new  IndexSearcher(path);   
        Hits hits =   null ;   
        Query query =   null ;   
        QueryParser qp =   new  QueryParser( " name " , new StandardAnalyzer());   
           
        query =  qp.parse( " lighter " );   
        hits =  searcher.search(query);   
        System.out.println(" 查找\ " lighter\ "  共 "   +  hits.length()  +  " 個結果 " );   
  
        query =  qp.parse( " javaeye " );   
        hits =  searcher.search(query);   
        System.out.println(" 查找\ " javaeye\ "  共 "   +  hits.length()  +  " 個結果 " );   
  
    }    
  
}   

運行結果:

查找 " lighter "  共2個結果   
查找 " javaeye "  共1個結果 


到現在我們已經可以用lucene建立索引了
下面介紹一下幾個功能來完善一下:
1.索引格式

其實索引目錄有兩種格式,

一種是除配置文件外,每一個Document獨立成爲一個文件(這種搜索起來會影響速度)。

另一種是全部的Document成一個文件,這樣屬於複合模式就快了。

2.索引文件可放的位置:

索引可以存放在兩個地方1.硬盤,2.內存
放在硬盤上可以用FSDirectory(),放在內存的用RAMDirectory()不過一關機就沒了

FSDirectory.getDirectory(File file, boolean  create)
FSDirectory.getDirectory(String path, boolean  create)

兩個工廠方法返回目錄
New RAMDirectory()就直接可以
再和

IndexWriter(Directory d, Analyzer a, boolean  create)

一配合就行了
如:

IndexWrtier indexWriter  =  new  IndexWriter(FSDirectory.getDirectory(“c:\\index”, true ), new StandardAnlyazer(), true );
IndexWrtier indexWriter  =  new  IndexWriter( new  RAMDirectory(), new  StandardAnlyazer(),true );

3.索引的合併
這個可用

IndexWriter.addIndexes(Directory[] dirs)

將目錄加進去
來看個例子:

public   void  UniteIndex() throws  IOException
    {
        IndexWriter writerDisk =   new  IndexWriter(FSDirectory.getDirectory( " c:\\indexDisk" ,  true ), new  StandardAnalyzer(), true );
        Document docDisk =   new  Document();
        docDisk.add(new  Field( " name " , " 程序員之家 " ,Field.Store.YES,Field.Index.TOKENIZED));
        writerDisk.addDocument(docDisk);
        RAMDirectory ramDir =   new  RAMDirectory();
        IndexWriter writerRam =   new  IndexWriter(ramDir, new  StandardAnalyzer(), true );
        Document docRam =   new  Document();
        docRam.add(new  Field( " name " , " 程序員雜誌 " ,Field.Store.YES,Field.Index.TOKENIZED));
        writerRam.addDocument(docRam);
        writerRam.close();// 這個方法非常重要,是必須調用的 
        writerDisk.addIndexes(new  Directory[] {ramDir} );
        writerDisk.close();
    } 
     public   void UniteSearch()  throws  ParseException, IOException
    {
        QueryParser queryParser =   new  QueryParser( " name " , new StandardAnalyzer());
        Query query =  queryParser.parse( " 程序員 " );
        IndexSearcher indexSearcher = new  IndexSearcher( " c:\\indexDisk " );
        Hits hits =  indexSearcher.search(query);
        System.out.println(" 找到了 " + hits.length() + " 結果 " );
        for ( int  i = 0 ;i
        {
            Document doc =  hits.doc(i);
            System.out.println(doc.get(" name " ));
        }
}


這個例子是將內存中的索引合併到硬盤上來.
注意:合併的時候一定要將被合併的那一方的IndexWriter的close()方法調用。

4.對索引的其它操作:
IndexReader類是用來操作索引的,它有對Document,Field的刪除等操作。
下面一部分的內容是:全文的搜索
全文的搜索主要是用:IndexSearcher,Query,Hits,Document(都是Query的子類),有的時候用QueryParser
主要步驟:

1 . new  QueryParser(Field字段, new  分析器)
2 .Query query  = QueryParser.parser(“要查詢的字串”);這個地方我們可以用反射api看一下query究竟是什麼類型
3 . new  IndexSearcher(索引目錄).search(query);返回Hits
4 .用Hits.doc(n);可以遍歷出Document
5 .用Document可得到Field的具體信息了。

其實1 ,2兩步就是爲了弄出個Query 實例,究竟是什麼類型的看分析器了。

拿以前的例子來說吧

QueryParser queryParser  =  new  QueryParser( " name " , new  StandardAnalyzer());
        Query query =  queryParser.parse( " 程序員 " );
/**/ /* 這裏返回的就是org.apache.lucene.search.PhraseQuery */ 
        IndexSearcher indexSearcher = new  IndexSearcher( " c:\\indexDisk " );
        Hits hits =  indexSearcher.search(query);


不管是什麼類型,無非返回的就是Query的子類,我們完全可以不用這兩步直接new個Query的子類的實例就ok了,不過一般還是用這兩步因爲它返回的是PhraseQuery這個是非常強大的query子類它可以進行多字搜索用QueryParser可以設置各個關鍵字之間的關係這個是最常用的了。
IndexSearcher:
其實IndexSearcher它內部自帶了一個IndexReader用來讀取索引的,IndexSearcher有個close()方法,這個方法不是用來關閉IndexSearche的是用來關閉自帶的IndexReader。

QueryParser呢可以用parser.setOperator()來設置各個關鍵字之間的關係(與還是或)它可以自動通過空格從字串裏面將關鍵字分離出來。
注意:用QueryParser搜索的時候分析器一定的和建立索引時候用的分析器是一樣的。
Query:
可以看一個lucene2.0的幫助文檔有很多的子類:
BooleanQuery, ConstantScoreQuery, ConstantScoreRangeQuery, DisjunctionMaxQuery,FilteredQuery, MatchAllDocsQuery, MultiPhraseQuery, MultiTermQuery,PhraseQuery, PrefixQuery, RangeQuery, SpanQuery, TermQuery
各自有用法看一下文檔就能知道它們的用法了
下面一部分講一下lucene的分析器:
分析器是由分詞器和過濾器組成的,拿英文來說吧分詞器就是通過空格把單詞分開,過濾器就是把the,to,of等詞去掉不被搜索和索引。
我們最常用的是StandardAnalyzer()它是lucene的標準分析器它集成了內部的許多的分析器。
最後一部分了:lucene的高級搜索了
1.排序
Lucene有內置的排序用IndexSearcher.search(query,sort)但是功能並不理想。我們需要自己實現自定義的排序。
這樣的話得實現兩個接口: ScoreDocComparator,SortComparatorSource
用IndexSearcher.search(query,newSort(new SortField(String Field,SortComparatorSource)));
就看個例子吧:
這是一個建立索引的例子:

public   void  IndexSort() throws  IOException
{
        IndexWriter writer =   new  IndexWriter( " C:\\indexStore " , new StandardAnalyzer(), true );
        Document doc =   new  Document()
        doc.add(new  Field( " sort " , " 1 ",Field.Store.YES,Field.Index.TOKENIZED));
        writer.addDocument(doc);
        doc =   new  Document();
        doc.add(new  Field( " sort " , " 4 ",Field.Store.YES,Field.Index.TOKENIZED));
        writer.addDocument(doc);
        doc =   new  Document();
        doc.add(new  Field( " sort " , " 3 ",Field.Store.YES,Field.Index.TOKENIZED));
        writer.addDocument(doc);
        doc =   new  Document();
        doc.add(new  Field( " sort " , " 5 ",Field.Store.YES,Field.Index.TOKENIZED));
        writer.addDocument(doc);
        doc =   new  Document();
        doc.add(new  Field( " sort " , " 9 ",Field.Store.YES,Field.Index.TOKENIZED));
        writer.addDocument(doc);
        doc =   new  Document();
        doc.add(new  Field( " sort " , " 6 " ,Field.Store.YES,Field.Index.TOKENIZED));
        writer.addDocument(doc);
        doc =   new  Document();
        doc.add(new  Field( " sort " , " 7 ",Field.Store.YES,Field.Index.TOKENIZED));
        writer.addDocument(doc);
        writer.close();


下面是搜索的例子:
[code]
public void SearchSort1() throws IOException, ParseException
{
        IndexSearcher indexSearcher = newIndexSearcher("C:\\indexStore");
        QueryParser queryParser = newQueryParser("sort",new StandardAnalyzer());
        Query query =queryParser.parse("4");
       
        Hits hits =indexSearcher.search(query);
        System.out.println("有"+hits.length()+"個結果");
        Document doc = hits.doc(0);
       System.out.println(doc.get("sort"));
}
public void SearchSort2() throws IOException, ParseException
{
        IndexSearcher indexSearcher = newIndexSearcher("C:\\indexStore");
        Query query = new RangeQuery(newTerm("sort","1"),newTerm("sort","9"),true);//這個地方前面沒有提到,它是用於範圍的Query可以看一下幫助文檔.
        Hits hits =indexSearcher.search(query,new Sort(new SortField("sort",newMySortComparatorSource())));
        System.out.println("有"+hits.length()+"個結果");
        for(int i=0;i
        {
            Document doc= hits.doc(i);
           System.out.println(doc.get("sort"));
        }
}
public class MyScoreDocComparator implements ScoreDocComparator
{
    private Integer[]sort;
    public MyScoreDocComparator(String s,IndexReader reader,String fieldname) throws IOException
    {
        sort = new Integer[reader.maxDoc()];
        for(int i = 0;i
        {
            Document doc=reader.document(i);
            sort[i]=newInteger(doc.get("sort"));
        }
    }
    public int compare(ScoreDoc i, ScoreDoc j)
    {
        if(sort[i.doc]>sort[j.doc])
            return 1;
        if(sort[i.doc]
            return -1;
        return 0;
    }
    public int sortType()
    {
        return SortField.INT;
    }
    public Comparable sortValue(ScoreDoc i)
    {
        // TODO 自動生成方法存根
        return new Integer(sort[i.doc]);
    }
}
public class MySortComparatorSource implements SortComparatorSource
{
    private static final long serialVersionUID =-9189690812107968361L;
    public ScoreDocComparator newComparator(IndexReader reader,String fieldname)
            throwsIOException
    {
       if(fieldname.equals("sort"))
            return newMyScoreDocComparator("sort",reader,fieldname);
        return null;
    }
}[/code]
SearchSort1()輸出的結果沒有排序,SearchSort2()就排序了。
2.多域搜索MultiFieldQueryParser
如果想輸入關鍵字而不想關心是在哪個Field裏的就可以用MultiFieldQueryParser了
用它的構造函數即可後面的和一個Field一樣。
MultiFieldQueryParser. parse(String[] queries, String[] fields,BooleanClause.Occur[] flags, Analyzeranalyzer)                                         ~~~~~~~~~~~~~~~~~
第三個參數比較特殊這裏也是與以前lucene1.4.3不一樣的地方
看一個例子就知道了
String[] fields = {"filename", "contents", "description"};
 BooleanClause.Occur[] flags = {BooleanClause.Occur.SHOULD,
               BooleanClause.Occur.MUST,//在這個Field裏必須出現的
               BooleanClause.Occur.MUST_NOT};//在這個Field裏不能出現
 MultiFieldQueryParser.parse("query", fields, flags, analyzer);

1、lucene的索引不能太大,要不然效率會很低。大於1G的時候就必須考慮分佈索引的問題

2、不建議用多線程來建索引,產生的互鎖問題很麻煩。經常發現索引被lock,無法重新建立的情況

3、中文分詞是個大問題,目前免費的分詞效果都很差。如果有能力還是自己實現一個分詞模塊,用最短路徑的切分方法,網上有教材和demo源碼,可以參考。

4、建增量索引的時候很耗cpu,在訪問量大的時候會導致cpu的idle爲0

5、默認的評分機制不太合理,需要根據自己的業務定製

1 lucene簡介
1.1 什麼是lucene
    Lucene是一個全文搜索框架,而不是應用產品。因此它並不像www.baidu.com 或者google Desktop那麼拿來就能用,它只是提供了一種工具讓你能實現這些產品。
2 lucene的工作方式
    lucene提供的服務實際包含兩部分:一入一出。所謂入是寫入,即將你提供的源(本質是字符串)寫入索引或者將其從索引中刪除;所謂出是讀出,即向用戶提供全文搜索服務,讓用戶可以通過關鍵詞定位源。
2.1寫入流程
    源字符串首先經過analyzer處理,包括:分詞,分成一個個單詞;去除stopword(可選)。
將源中需要的信息加入Document的各個Field中,並把需要索引的Field索引起來,把需要存儲的Field存儲起來。
    將索引寫入存儲器,存儲器可以是內存或磁盤。
2.2讀出流程
    用戶提供搜索關鍵詞,經過analyzer處理。
對處理後的關鍵詞搜索索引找出對應的Document。
用戶根據需要從找到的Document中提取需要的Field。
3 一些需要知道的概念
3.1 analyzer
    Analyzer是分析器,它的作用是把一個字符串按某種規則劃分成一個個詞語,並去除其中的無效詞語,這裏說的無效詞語是指英文中的“of”、“the”,中文中的“的”、“地”等詞語,這些詞語在文章中大量出現,但是本身不包含什麼關鍵信息,去掉有利於縮小索引文件、提高效率、提高命中率。
  分詞的規則千變萬化,但目的只有一個:按語義劃分。這點在英文中比較容易實現,因爲英文本身就是以單詞爲單位的,已經用空格分開;而中文則必須以某種方法將連成一片的句子劃分成一個個詞語。具體劃分方法下面再詳細介紹,這裏只需瞭解分析器的概念即可。
3.2 document
  用戶提供的源是一條條記錄,它們可以是文本文件、字符串或者數據庫表的一條記錄等等。一條記錄經過索引之後,就是以一個Document的形式存儲在索引文件中的。用戶進行搜索,也是以Document列表的形式返回。
3.3 field
    一個Document可以包含多個信息域,例如一篇文章可以包含“標題”、“正文”、“最後修改時間”等信息域,這些信息域就是通過Field在Document中存儲的。
    Field有兩個屬性可選:存儲和索引。通過存儲屬性你可以控制是否對這個Field進行存儲;通過索引屬性你可以控制是否對該Field進行索引。這看起來似乎有些廢話,事實上對這兩個屬性的正確組合很重要,下面舉例說明:還是以剛纔的文章爲例子,我們需要對標題和正文進行全文搜索,所以我們要把索引屬性設置爲真,同時我們希望能直接從搜索結果中提取文章標題,所以我們把標題域的存儲屬性設置爲真,但是由於正文域太大了,我們爲了縮小索引文件大小,將正文域的存儲屬性設置爲假,當需要時再直接讀取文件;我們只是希望能從搜索解果中提取最後修改時間,不需要對它進行搜索,所以我們把最後修改時間域的存儲屬性設置爲真,索引屬性設置爲假。上面的三個域涵蓋了兩個屬性的三種組合,還有一種全爲假的沒有用到,事實上Field不允許你那麼設置,因爲既不存儲又不索引的域是沒有意義的。
3.4 term
  term是搜索的最小單位,它表示文檔的一個詞語,term由兩部分組成:它表示的詞語和這個詞語所出現的field。
3.5 tocken
    tocken是term的一次出現,它包含trem文本和相應的起止偏移,以及一個類型字符串。一句話中可以出現多次相同的詞語,它們都用同一個term表示,但是用不同的tocken,每個tocken標記該詞語出現的地方。
3.6 segment
    添加索引時並不是每個document都馬上添加到同一個索引文件,它們首先被寫入到不同的小文件,然後再合併成一個大索引文件,這裏每個小文件都是一個segment。
4 如何建索引
4.1 最簡單的能完成索引的代碼片斷
IndexWriter writer = new IndexWriter(“/data/index/”, new StandardAnalyzer(), true);
Document doc = new Document();
doc.add(new Field("title", "lucene introduction", Field.Store.YES, Field.Index.TOKENIZED));
doc.add(new Field("content", "lucene works well", Field.Store.YES, Field.Index.TOKENIZED));
writer.addDocument(doc);
writer.optimize();
writer.close();
下面我們分析一下這段代碼。
首先我們創建了一個writer,並指定存放索引的目錄爲“/data/index”,使用的分析器爲StandardAnalyzer,第三個參數說明如果已經有索引文件在索引目錄下,我們將覆蓋它們。然後我們新建一個document。
  我們向document添加一個field,名字是“title”,內容是“lucene introduction”,對它進行存儲並索引。再添加一個名字是“content”的field,內容是“lucene works well”,也是存儲並索引。
然後我們將這個文檔添加到索引中,如果有多個文檔,可以重複上面的操作,創建document並添加。
添加完所有document,我們對索引進行優化,優化主要是將多個segment合併到一個,有利於提高索引速度。
   隨後將writer關閉,這點很重要。
   對,創建索引就這麼簡單!
  當然你可能修改上面的代碼獲得更具個性化的服務。
4.2 索引文本文件
    如果你想把純文本文件索引起來,而不想自己將它們讀入字符串創建field,你可以用下面的代碼創建field:
Field field = new Field("content", new FileReader(file));
    這裏的file就是該文本文件。該構造函數實際上是讀去文件內容,並對其進行索引,但不存儲。



Lucene 2 教程

Lucene是apache組織的一個用java實現全文搜索引擎的開源項目。 其功能非常的強大,api也很簡單。總得來說用Lucene來進行建立 和搜索和操作數據庫是差不多的(有點像),Document可以看作是 數據庫的一行記錄,Field可以看作是數據庫的字段。用lucene實 現搜索引擎就像用JDBC實現連接數據庫一樣簡單。

Lucene2.0,它與以前廣泛應用和介紹的Lucene 1.4.3並不兼容。 Lucene2.0的下載地址是http://apache.justdn.org/lucene/java/


例子一 :

1、在windows系統下的的C盤,建一個名叫s的文件夾,在該文件夾裏面隨便建三個txt文件,隨便起名啦,就叫"1.txt","2.txt"和"3.txt"啦 
其中1.txt的內容如下:

中華人民共和國   
全國人民   
2006年  

而"2.txt"和"3.txt"的內容也可以隨便寫幾寫,這裏懶寫,就複製一個和1.txt文件的內容一樣吧

2、下載lucene包,放在classpath路徑中 
建立索引:

package lighter.javaeye.com;   
  
import java.io.BufferedReader;   
import  java.io.File;   
import java.io.FileInputStream;   
import  java.io.IOException;   
import java.io.InputStreamReader;   
import  java.util.Date;   
  
import  org.apache.lucene.analysis.Analyzer;   
import org.apache.lucene.analysis.standard.StandardAnalyzer;   
import org.apache.lucene.document.Document;   
import org.apache.lucene.document.Field;   
import org.apache.lucene.index.IndexWriter;   
  
/** */ /**   
 * author lighter date 2006-8-7  
  */   
public   class TextFileIndexer  {   
    public   static   void  main(String[] args)  throws Exception  {   
        /**/ /*  指明要索引文件夾的位置,這裏是C盤的S文件夾下 */   
        File fileDir =   new  File( " c:\\s " );   
  
        /**/ /*  這裏放索引文件的位置  */   
        File indexDir =   new  File( " c:\\index " );   
        Analyzer luceneAnalyzer =   new  StandardAnalyzer();   
        IndexWriter indexWriter =   new  IndexWriter(indexDir, luceneAnalyzer,   
                true );   
        File[] textFiles =  fileDir.listFiles();   
        long  startTime  =   new Date().getTime();   
           
        // 增加document到索引去    
        for  ( int  i  =   0 ; i  < textFiles.length; i ++ )  {   
            if  (textFiles[i].isFile()   
                    &&  textFiles[i].getName().endsWith( " .txt " ))  {   
                System.out.println(" File  "   + textFiles[i].getCanonicalPath()   
                        +   " 正在被索引. " );   
                String temp =  FileReaderAll(textFiles[i].getCanonicalPath(),   
                        " GBK " );   
                System.out.println(temp);   
                Document document =   new  Document();   
                Field FieldPath =   new  Field( " path ", textFiles[i].getPath(),   
                        Field.Store.YES, Field.Index.NO);   
                Field FieldBody =   new  Field( " body ", temp, Field.Store.YES,   
                        Field.Index.TOKENIZED,   
                        Field.TermVector.WITH_POSITIONS_OFFSETS);   
                document.add(FieldPath);   
                document.add(FieldBody);   
                indexWriter.addDocument(document);   
            }   
        }   
        // optimize()方法是對索引進行優化    
        indexWriter.optimize();   
        indexWriter.close();   
           
        // 測試一下索引的時間    
        long  endTime  =   new  Date().getTime();   
        System.out   
                .println(" 這花費了"   
                        +  (endTime  -  startTime)   
                        +   "  毫秒來把文檔增加到索引裏面去! "   
                        +  fileDir.getPath());   
    }    
  
     public   static String FileReaderAll(String FileName, String charset)   
            throws  IOException  {   
        BufferedReader reader =   new  BufferedReader( new InputStreamReader(   
                new  FileInputStream(FileName), charset));   
        String line =   new  String();   
        String temp =   new  String();   
           
        while  ((line  =  reader.readLine())  !=   null)  {   
            temp +=  line;   
        }   
        reader.close();   
        return  temp;   
    }    
}  

索引的結果:

File C:\s\ 1 .txt正在被索引.   
中華人民共和國全國人民2006年   
File C:\s\ 2 .txt正在被索引.   
中華人民共和國全國人民2006年   
File C:\s\ 3 .txt正在被索引.   
中華人民共和國全國人民2006年   
這花費了297 毫秒來把文檔增加到索引裏面去 ! c:\s  


3、建立了索引之後,查詢啦....

package  lighter.javaeye.com;   
  
import java.io.IOException;   
  
import org.apache.lucene.analysis.Analyzer;   
import org.apache.lucene.analysis.standard.StandardAnalyzer;   
import  org.apache.lucene.queryParser.ParseException;   
import org.apache.lucene.queryParser.QueryParser;   
import org.apache.lucene.search.Hits;   
import org.apache.lucene.search.IndexSearcher;   
import org.apache.lucene.search.Query;   
  
public   class TestQuery  {   
    public   static   void  main(String[] args)  throws IOException, ParseException  {   
        Hits hits =   null ;   
        String queryString =   " 中華 ";   
        Query query =   null ;   
        IndexSearcher searcher =   new  IndexSearcher( " c:\\index " );   
  
        Analyzer analyzer =   new  StandardAnalyzer();   
        try   {   
            QueryParser qp =   new  QueryParser( " body ", analyzer);   
            query =  qp.parse(queryString);   
        }  catch  (ParseException e)  {   
        }   
        if  (searcher  !=   null )  {   
            hits =  searcher.search(query);   
            if  (hits.length()  >   0 )  {   
                System.out.println(" 找到: "  +  hits.length()  +   "  個結果! " );   
            }   
        }   
    }  
  
}   

其運行結果:

找到: 3  個結果!

 

Lucene 其實很簡單的,它最主要就是做兩件事:建立索引和進行搜索 
來看一些在lucene中使用的術語,這裏並不打算作詳細的介紹,只是點一下而已----因爲這一個世界有一種好東西,叫搜索。

IndexWriter:lucene中最重要的的類之一,它主要是用來將文檔加入索引,同時控制索引過程中的一些參數使用。

Analyzer:分析器,主要用於分析搜索引擎遇到的各種文本。常用的有StandardAnalyzer分析器,StopAnalyzer分析器,WhitespaceAnalyzer分析器等。

Directory:索引存放的位置;lucene提供了兩種索引存放的位置,一種是磁盤,一種是內存。一般情況將索引放在磁盤上;相應地lucene提供了FSDirectory和RAMDirectory兩個類。

Document:文檔;Document相當於一個要進行索引的單元,任何可以想要被索引的文件都必須轉化爲Document對象才能進行索引。

Field:字段。

IndexSearcher:是lucene中最基本的檢索工具,所有的檢索都會用到IndexSearcher工具;

Query:查詢,lucene中支持模糊查詢,語義查詢,短語查詢,組合查詢等等,如有TermQuery,BooleanQuery,RangeQuery,WildcardQuery等一些類。

QueryParser: 是一個解析用戶輸入的工具,可以通過掃描用戶輸入的字符串,生成Query對象。

Hits:在搜索完成之後,需要把搜索結果返回並顯示給用戶,只有這樣纔算是完成搜索的目的。在lucene中,搜索的結果的集合是用Hits類的實例來表示的。

上面作了一大堆名詞解釋,下面就看幾個簡單的實例吧: 
1、簡單的的StandardAnalyzer測試例子

 

package  lighter.javaeye.com;   
  
import java.io.IOException;   
import java.io.StringReader;   
  
import org.apache.lucene.analysis.Analyzer;   
import  org.apache.lucene.analysis.Token;   
import org.apache.lucene.analysis.TokenStream;   
import org.apache.lucene.analysis.standard.StandardAnalyzer;   
  
public   class StandardAnalyzerTest    
{   
     // 構造函數,    
     public StandardAnalyzerTest()   
    {   
    }    
     public   static  void  main(String[] args)    
    {   
        // 生成一個StandardAnalyzer對象    
        Analyzer aAnalyzer =   new  StandardAnalyzer();   
        // 測試字符串   
        StringReader sr =   new  StringReader( "lighter javaeye com is the are on ");   
        // 生成TokenStream對象    
        TokenStream ts =  aAnalyzer.tokenStream( " name ", sr);    
        try   {   
            int  i = 0 ;   
            Token t =  ts.next();   
            while (t != null )   
            {   
                // 輔助輸出時顯示行號   
                i++ ;   
                // 輸出處理後的字符   
                System.out.println(" 第 " + i + " 行: " + t.termText());   
                // 取得下一個字符   
                t= ts.next();   
            }   
        }  catch  (IOException e)  {   
            e.printStackTrace();   
        }   
    }    
}    

顯示結果:

第1行:lighter 
第2行:javaeye 
第3行:com

提示一下: 
StandardAnalyzer是lucene中內置的"標準分析器",可以做如下功能: 
1、對原有句子按照空格進行了分詞 
2、所有的大寫字母都可以能轉換爲小寫的字母 
3、可以去掉一些沒有用處的單詞,例如"is","the","are"等單詞,也刪除了所有的標點 
查看一下結果與"newStringReader("lighter javaeye com is the are on")"作一個比較就清楚明瞭。 
這裏不對其API進行解釋了,具體見lucene的官方文檔。需要注意一點,這裏的代碼使用的是lucene2的API,與1.43版有一些明顯的差別。

2、看另一個實例,簡單地建立索引,進行搜索

package lighter.javaeye.com;   
import org.apache.lucene.analysis.standard.StandardAnalyzer;   
import org.apache.lucene.document.Document;   
import org.apache.lucene.document.Field;   
import  org.apache.lucene.index.IndexWriter;   
import org.apache.lucene.queryParser.QueryParser;   
import org.apache.lucene.search.Hits;   
import org.apache.lucene.search.IndexSearcher;   
import org.apache.lucene.search.Query;   
import org.apache.lucene.store.FSDirectory;   
  
public   class FSDirectoryTest  {   
  
     // 建立索引的路徑    
     public   static  final  String path  =   " c:\\index2 ";   
  
    public   static   void  main(String[] args)  throws Exception  {   
        Document doc1 =   new  Document();   
        doc1.add( new  Field( " name " ,  "lighter javaeye com " ,Field.Store.YES,Field.Index.TOKENIZED));   
  
        Document doc2 =   new  Document();   
        doc2.add(new  Field( " name " ,  " lighter blog ",Field.Store.YES,Field.Index.TOKENIZED));   
  
        IndexWriter writer =   new  IndexWriter(FSDirectory.getDirectory(path,  true),  new  StandardAnalyzer(),  true );   
        writer.setMaxFieldLength(3 );   
        writer.addDocument(doc1);   
        writer.setMaxFieldLength(3 );   
        writer.addDocument(doc2);   
        writer.close();   
  
        IndexSearcher searcher =   new  IndexSearcher(path);   
        Hits hits =   null ;   
        Query query =   null ;   
        QueryParser qp =   new  QueryParser( " name " , new StandardAnalyzer());   
           
        query =  qp.parse( " lighter " );   
        hits =  searcher.search(query);   
        System.out.println(" 查找\ " lighter\ "  共 "   +  hits.length()  +  " 個結果 " );   
  
        query =  qp.parse( " javaeye " );   
        hits =  searcher.search(query);   
        System.out.println(" 查找\ " javaeye\ "  共 "   +  hits.length()  +  " 個結果 " );   
  
    }    
  
}   

運行結果:

查找 " lighter "  共2個結果   
查找 " javaeye "  共1個結果 


到現在我們已經可以用lucene建立索引了
下面介紹一下幾個功能來完善一下:
1.索引格式

其實索引目錄有兩種格式,

一種是除配置文件外,每一個Document獨立成爲一個文件(這種搜索起來會影響速度)。

另一種是全部的Document成一個文件,這樣屬於複合模式就快了。

2.索引文件可放的位置:

索引可以存放在兩個地方1.硬盤,2.內存
放在硬盤上可以用FSDirectory(),放在內存的用RAMDirectory()不過一關機就沒了

FSDirectory.getDirectory(File file, boolean  create)
FSDirectory.getDirectory(String path, boolean  create)

兩個工廠方法返回目錄
New RAMDirectory()就直接可以
再和

IndexWriter(Directory d, Analyzer a, boolean  create)

一配合就行了
如:

IndexWrtier indexWriter  =  new  IndexWriter(FSDirectory.getDirectory(“c:\\index”, true ), new StandardAnlyazer(), true );
IndexWrtier indexWriter  =  new  IndexWriter( new  RAMDirectory(), new  StandardAnlyazer(),true );

3.索引的合併
這個可用

IndexWriter.addIndexes(Directory[] dirs)

將目錄加進去
來看個例子:

public   void  UniteIndex() throws  IOException
    {
        IndexWriter writerDisk =   new  IndexWriter(FSDirectory.getDirectory( " c:\\indexDisk" ,  true ), new  StandardAnalyzer(), true );
        Document docDisk =   new  Document();
        docDisk.add(new  Field( " name " , " 程序員之家 " ,Field.Store.YES,Field.Index.TOKENIZED));
        writerDisk.addDocument(docDisk);
        RAMDirectory ramDir =   new  RAMDirectory();
        IndexWriter writerRam =   new  IndexWriter(ramDir, new  StandardAnalyzer(), true );
        Document docRam =   new  Document();
        docRam.add(new  Field( " name " , " 程序員雜誌 " ,Field.Store.YES,Field.Index.TOKENIZED));
        writerRam.addDocument(docRam);
        writerRam.close();// 這個方法非常重要,是必須調用的 
        writerDisk.addIndexes(new  Directory[] {ramDir} );
        writerDisk.close();
    } 
     public   void UniteSearch()  throws  ParseException, IOException
    {
        QueryParser queryParser =   new  QueryParser( " name " , new StandardAnalyzer());
        Query query =  queryParser.parse( " 程序員 " );
        IndexSearcher indexSearcher = new  IndexSearcher( " c:\\indexDisk " );
        Hits hits =  indexSearcher.search(query);
        System.out.println(" 找到了 " + hits.length() + " 結果 " );
        for ( int  i = 0 ;i
        {
            Document doc =  hits.doc(i);
            System.out.println(doc.get(" name " ));
        }
}


這個例子是將內存中的索引合併到硬盤上來.
注意:合併的時候一定要將被合併的那一方的IndexWriter的close()方法調用。

4.對索引的其它操作:
IndexReader類是用來操作索引的,它有對Document,Field的刪除等操作。
下面一部分的內容是:全文的搜索
全文的搜索主要是用:IndexSearcher,Query,Hits,Document(都是Query的子類),有的時候用QueryParser
主要步驟:

1 . new  QueryParser(Field字段, new  分析器)
2 .Query query  = QueryParser.parser(“要查詢的字串”);這個地方我們可以用反射api看一下query究竟是什麼類型
3 . new  IndexSearcher(索引目錄).search(query);返回Hits
4 .用Hits.doc(n);可以遍歷出Document
5 .用Document可得到Field的具體信息了。

其實1 ,2兩步就是爲了弄出個Query 實例,究竟是什麼類型的看分析器了。

拿以前的例子來說吧

QueryParser queryParser  =  new  QueryParser( " name " , new  StandardAnalyzer());
        Query query =  queryParser.parse( " 程序員 " );
/**/ /* 這裏返回的就是org.apache.lucene.search.PhraseQuery */ 
        IndexSearcher indexSearcher = new  IndexSearcher( " c:\\indexDisk " );
        Hits hits =  indexSearcher.search(query);


不管是什麼類型,無非返回的就是Query的子類,我們完全可以不用這兩步直接new個Query的子類的實例就ok了,不過一般還是用這兩步因爲它返回的是PhraseQuery這個是非常強大的query子類它可以進行多字搜索用QueryParser可以設置各個關鍵字之間的關係這個是最常用的了。
IndexSearcher:
其實IndexSearcher它內部自帶了一個IndexReader用來讀取索引的,IndexSearcher有個close()方法,這個方法不是用來關閉IndexSearche的是用來關閉自帶的IndexReader。

QueryParser呢可以用parser.setOperator()來設置各個關鍵字之間的關係(與還是或)它可以自動通過空格從字串裏面將關鍵字分離出來。
注意:用QueryParser搜索的時候分析器一定的和建立索引時候用的分析器是一樣的。
Query:
可以看一個lucene2.0的幫助文檔有很多的子類:
BooleanQuery, ConstantScoreQuery, ConstantScoreRangeQuery, DisjunctionMaxQuery,FilteredQuery, MatchAllDocsQuery, MultiPhraseQuery, MultiTermQuery,PhraseQuery, PrefixQuery, RangeQuery, SpanQuery, TermQuery
各自有用法看一下文檔就能知道它們的用法了
下面一部分講一下lucene的分析器:
分析器是由分詞器和過濾器組成的,拿英文來說吧分詞器就是通過空格把單詞分開,過濾器就是把the,to,of等詞去掉不被搜索和索引。
我們最常用的是StandardAnalyzer()它是lucene的標準分析器它集成了內部的許多的分析器。
最後一部分了:lucene的高級搜索了
1.排序
Lucene有內置的排序用IndexSearcher.search(query,sort)但是功能並不理想。我們需要自己實現自定義的排序。
這樣的話得實現兩個接口: ScoreDocComparator,SortComparatorSource
用IndexSearcher.search(query,newSort(new SortField(String Field,SortComparatorSource)));
就看個例子吧:
這是一個建立索引的例子:

public   void  IndexSort() throws  IOException
{
        IndexWriter writer =   new  IndexWriter( " C:\\indexStore " , new StandardAnalyzer(), true );
        Document doc =   new  Document()
        doc.add(new  Field( " sort " , " 1 ",Field.Store.YES,Field.Index.TOKENIZED));
        writer.addDocument(doc);
        doc =   new  Document();
        doc.add(new  Field( " sort " , " 4 ",Field.Store.YES,Field.Index.TOKENIZED));
        writer.addDocument(doc);
        doc =   new  Document();
        doc.add(new  Field( " sort " , " 3 ",Field.Store.YES,Field.Index.TOKENIZED));
        writer.addDocument(doc);
        doc =   new  Document();
        doc.add(new  Field( " sort " , " 5 ",Field.Store.YES,Field.Index.TOKENIZED));
        writer.addDocument(doc);
        doc =   new  Document();
        doc.add(new  Field( " sort " , " 9 ",Field.Store.YES,Field.Index.TOKENIZED));
        writer.addDocument(doc);
        doc =   new  Document();
        doc.add(new  Field( " sort " , " 6 " ,Field.Store.YES,Field.Index.TOKENIZED));
        writer.addDocument(doc);
        doc =   new  Document();
        doc.add(new  Field( " sort " , " 7 ",Field.Store.YES,Field.Index.TOKENIZED));
        writer.addDocument(doc);
        writer.close();


下面是搜索的例子:
[code]
public void SearchSort1() throws IOException, ParseException
{
        IndexSearcher indexSearcher = newIndexSearcher("C:\\indexStore");
        QueryParser queryParser = newQueryParser("sort",new StandardAnalyzer());
        Query query =queryParser.parse("4");
       
        Hits hits =indexSearcher.search(query);
        System.out.println("有"+hits.length()+"個結果");
        Document doc = hits.doc(0);
       System.out.println(doc.get("sort"));
}
public void SearchSort2() throws IOException, ParseException
{
        IndexSearcher indexSearcher = newIndexSearcher("C:\\indexStore");
        Query query = new RangeQuery(newTerm("sort","1"),newTerm("sort","9"),true);//這個地方前面沒有提到,它是用於範圍的Query可以看一下幫助文檔.
        Hits hits =indexSearcher.search(query,new Sort(new SortField("sort",newMySortComparatorSource())));
        System.out.println("有"+hits.length()+"個結果");
        for(int i=0;i
        {
            Document doc= hits.doc(i);
           System.out.println(doc.get("sort"));
        }
}
public class MyScoreDocComparator implements ScoreDocComparator
{
    private Integer[]sort;
    public MyScoreDocComparator(String s,IndexReader reader,String fieldname) throws IOException
    {
        sort = new Integer[reader.maxDoc()];
        for(int i = 0;i
        {
            Document doc=reader.document(i);
            sort[i]=newInteger(doc.get("sort"));
        }
    }
    public int compare(ScoreDoc i, ScoreDoc j)
    {
        if(sort[i.doc]>sort[j.doc])
            return 1;
        if(sort[i.doc]
            return -1;
        return 0;
    }
    public int sortType()
    {
        return SortField.INT;
    }
    public Comparable sortValue(ScoreDoc i)
    {
        // TODO 自動生成方法存根
        return new Integer(sort[i.doc]);
    }
}
public class MySortComparatorSource implements SortComparatorSource
{
    private static final long serialVersionUID =-9189690812107968361L;
    public ScoreDocComparator newComparator(IndexReader reader,String fieldname)
            throwsIOException
    {
       if(fieldname.equals("sort"))
            return newMyScoreDocComparator("sort",reader,fieldname);
        return null;
    }
}[/code]
SearchSort1()輸出的結果沒有排序,SearchSort2()就排序了。
2.多域搜索MultiFieldQueryParser
如果想輸入關鍵字而不想關心是在哪個Field裏的就可以用MultiFieldQueryParser了
用它的構造函數即可後面的和一個Field一樣。
MultiFieldQueryParser. parse(String[] queries, String[] fields,BooleanClause.Occur[] flags, Analyzeranalyzer)                                         ~~~~~~~~~~~~~~~~~
第三個參數比較特殊這裏也是與以前lucene1.4.3不一樣的地方
看一個例子就知道了
String[] fields = {"filename", "contents", "description"};
 BooleanClause.Occur[] flags = {BooleanClause.Occur.SHOULD,
               BooleanClause.Occur.MUST,//在這個Field裏必須出現的
               BooleanClause.Occur.MUST_NOT};//在這個Field裏不能出現
 MultiFieldQueryParser.parse("query", fields, flags, analyzer);

1、lucene的索引不能太大,要不然效率會很低。大於1G的時候就必須考慮分佈索引的問題

2、不建議用多線程來建索引,產生的互鎖問題很麻煩。經常發現索引被lock,無法重新建立的情況

3、中文分詞是個大問題,目前免費的分詞效果都很差。如果有能力還是自己實現一個分詞模塊,用最短路徑的切分方法,網上有教材和demo源碼,可以參考。

4、建增量索引的時候很耗cpu,在訪問量大的時候會導致cpu的idle爲0

5、默認的評分機制不太合理,需要根據自己的業務定製

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章