Lucene 2 教程

本文摘自:http://www.blogjava.net/liuwentao253/archive/2007/01/08/92401.html


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路径中
建立索引:

Java代码 复制代码  收藏代码
  1. package  lighter.iteye.com;      
  2.     
  3. import  java.io.BufferedReader;      
  4. import  java.io.File;      
  5. import  java.io.FileInputStream;      
  6. import  java.io.IOException;      
  7. import  java.io.InputStreamReader;      
  8. import  java.util.Date;      
  9.     
  10. import  org.apache.lucene.analysis.Analyzer;      
  11. import  org.apache.lucene.analysis.standard.StandardAnalyzer;      
  12. import  org.apache.lucene.document.Document;      
  13. import  org.apache.lucene.document.Field;      
  14. import  org.apache.lucene.index.IndexWriter;      
  15.     
  16. /**     
  17. * author lighter date 2006-8-7    
  18.  */      
  19. public   class  TextFileIndexer  {      
  20.     public   static   void  main(String[] args)  throws  Exception  {      
  21.         /*  指明要索引文件夹的位置,这里是C盘的S文件夹下  */      
  22.        File fileDir  =   new  File( " c:\\s " );      
  23.     
  24.         /*  这里放索引文件的位置  */      
  25.        File indexDir  =   new  File( " c:\\index " );      
  26.        Analyzer luceneAnalyzer  =   new  StandardAnalyzer();      
  27.        IndexWriter indexWriter  =   new  IndexWriter(indexDir, luceneAnalyzer,      
  28.                 true );      
  29.        File[] textFiles  =  fileDir.listFiles();      
  30.         long  startTime  =   new  Date().getTime();      
  31.              
  32.         // 增加document到索引去       
  33.          for  ( int  i  =   0 ; i  <  textFiles.length; i ++ )  {      
  34.             if  (textFiles[i].isFile()      
  35.                     &&  textFiles[i].getName().endsWith( " .txt " ))  {      
  36.                System.out.println( " File  "   +  textFiles[i].getCanonicalPath()      
  37.                         +   " 正在被索引. " );      
  38.                String temp  =  FileReaderAll(textFiles[i].getCanonicalPath(),      
  39.                         " GBK " );      
  40.                System.out.println(temp);      
  41.                Document document  =   new  Document();      
  42.                Field FieldPath  =   new  Field( " path " , textFiles[i].getPath(),      
  43.                        Field.Store.YES, Field.Index.NO);      
  44.                Field FieldBody  =   new  Field( " body " , temp, Field.Store.YES,      
  45.                        Field.Index.TOKENIZED,      
  46.                        Field.TermVector.WITH_POSITIONS_OFFSETS);      
  47.                document.add(FieldPath);      
  48.                document.add(FieldBody);      
  49.                indexWriter.addDocument(document);      
  50.            }       
  51.        }       
  52.         // optimize()方法是对索引进行优化       
  53.         indexWriter.optimize();      
  54.        indexWriter.close();      
  55.              
  56.         // 测试一下索引的时间       
  57.          long  endTime  =   new  Date().getTime();      
  58.        System.out      
  59.                .println( " 这花费了 "      
  60.                         +  (endTime  -  startTime)      
  61.                         +   "  毫秒来把文档增加到索引里面去! "      
  62.                         +  fileDir.getPath());      
  63.    }       
  64.     
  65.     public   static  String FileReaderAll(String FileName, String charset)      
  66.             throws  IOException  {      
  67.        BufferedReader reader  =   new  BufferedReader( new  InputStreamReader(      
  68.                 new  FileInputStream(FileName), charset));      
  69.        String line  =   new  String();      
  70.        String temp  =   new  String();      
  71.              
  72.         while  ((line  =  reader.readLine())  !=   null )  {      
  73.            temp  +=  line;      
  74.        }       
  75.        reader.close();      
  76.         return  temp;      
  77.    }       
  78.     
 package  lighter.iteye.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、建立了索引之后,查询啦....

Java代码 复制代码  收藏代码
  1. package  lighter.iteye.com;      
  2.      
  3.  import  java.io.IOException;      
  4.      
  5.  import  org.apache.lucene.analysis.Analyzer;      
  6.  import  org.apache.lucene.analysis.standard.StandardAnalyzer;      
  7.  import  org.apache.lucene.queryParser.ParseException;      
  8.  import  org.apache.lucene.queryParser.QueryParser;      
  9.  import  org.apache.lucene.search.Hits;      
  10.  import  org.apache.lucene.search.IndexSearcher;      
  11.  import  org.apache.lucene.search.Query;      
  12.      
  13.  public   class  TestQuery  {      
  14.      public   static   void  main(String[] args)  throws  IOException, ParseException  {      
  15.         Hits hits  =   null ;      
  16.         String queryString  =   " 中华 " ;      
  17.         Query query  =   null ;      
  18.         IndexSearcher searcher  =   new  IndexSearcher( " c:\\index " );      
  19.      
  20.         Analyzer analyzer  =   new  StandardAnalyzer();      
  21.          try   {      
  22.             QueryParser qp  =   new  QueryParser( " body " , analyzer);      
  23.             query  =  qp.parse(queryString);      
  24.         }   catch  (ParseException e)  {      
  25.         }       
  26.          if  (searcher  !=   null )  {      
  27.             hits  =  searcher.search(query);      
  28.              if  (hits.length()  >   0 )  {      
  29.                 System.out.println( " 找到: "   +  hits.length()  +   "  个结果! " );      
  30.             }       
  31.         }       
  32.     }     
  33.      
  34. }    
package  lighter.iteye.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测试例子

Java代码 复制代码  收藏代码
  1. package  lighter.iteye.com;      
  2.      
  3.  import  java.io.IOException;      
  4.  import  java.io.StringReader;      
  5.      
  6.  import  org.apache.lucene.analysis.Analyzer;      
  7.  import  org.apache.lucene.analysis.Token;      
  8.  import  org.apache.lucene.analysis.TokenStream;      
  9.  import  org.apache.lucene.analysis.standard.StandardAnalyzer;      
  10.      
  11.  public   class  StandardAnalyzerTest       
  12.  {      
  13.      // 构造函数,       
  14.       public  StandardAnalyzerTest()      
  15.      {      
  16.     }       
  17.      public   static   void  main(String[] args)       
  18.      {      
  19.          // 生成一个StandardAnalyzer对象       
  20.          Analyzer aAnalyzer  =   new  StandardAnalyzer();      
  21.          // 测试字符串       
  22.          StringReader sr  =   new  StringReader( " lighter javaeye com is the are on " );      
  23.          // 生成TokenStream对象       
  24.          TokenStream ts  =  aAnalyzer.tokenStream( " name " , sr);       
  25.          try   {      
  26.              int  i = 0 ;      
  27.             Token t  =  ts.next();      
  28.              while (t != null )      
  29.              {      
  30.                  // 辅助输出时显示行号       
  31.                  i ++ ;      
  32.                  // 输出处理后的字符       
  33.                  System.out.println( " 第 " + i + " 行: " + t.termText());      
  34.                  // 取得下一个字符       
  35.                  t = ts.next();      
  36.             }       
  37.         }   catch  (IOException e)  {      
  38.             e.printStackTrace();      
  39.         }       
  40.     }       
  41. }   
package  lighter.iteye.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"等单词,也删除了所有的标点
查看一下结果与"new StringReader("lighter javaeye com is the are on")"作一个比较就清楚明了。
这里不对其API进行解释了,具体见lucene的官方文档。需要注意一点,这里的代码使用的是lucene2的API,与1.43版有一些明显的差别。

2、看另一个实例,简单地建立索引,进行搜索

Java代码 复制代码  收藏代码
  1. package  lighter.iteye.com;      
  2.  import  org.apache.lucene.analysis.standard.StandardAnalyzer;      
  3.  import  org.apache.lucene.document.Document;      
  4.  import  org.apache.lucene.document.Field;      
  5.  import  org.apache.lucene.index.IndexWriter;      
  6.  import  org.apache.lucene.queryParser.QueryParser;      
  7.  import  org.apache.lucene.search.Hits;      
  8.  import  org.apache.lucene.search.IndexSearcher;      
  9.  import  org.apache.lucene.search.Query;      
  10.  import  org.apache.lucene.store.FSDirectory;      
  11.      
  12.  public   class  FSDirectoryTest  {      
  13.      
  14.      // 建立索引的路径       
  15.       public   static   final  String path  =   " c:\\index2 " ;      
  16.      
  17.      public   static   void  main(String[] args)  throws  Exception  {      
  18.         Document doc1  =   new  Document();      
  19.         doc1.add(  new  Field( " name " ,  " lighter javaeye com " ,Field.Store.YES,Field.Index.TOKENIZED));      
  20.      
  21.         Document doc2  =   new  Document();      
  22.         doc2.add( new  Field( " name " ,  " lighter blog " ,Field.Store.YES,Field.Index.TOKENIZED));      
  23.      
  24.         IndexWriter writer  =   new  IndexWriter(FSDirectory.getDirectory(path,  true ),  new  StandardAnalyzer(),  true );      
  25.         writer.setMaxFieldLength( 3 );      
  26.         writer.addDocument(doc1);      
  27.         writer.setMaxFieldLength( 3 );      
  28.         writer.addDocument(doc2);      
  29.         writer.close();      
  30.      
  31.         IndexSearcher searcher  =   new  IndexSearcher(path);      
  32.         Hits hits  =   null ;      
  33.         Query query  =   null ;      
  34.         QueryParser qp  =   new  QueryParser( " name " , new  StandardAnalyzer());      
  35.               
  36.         query  =  qp.parse( " lighter " );      
  37.         hits  =  searcher.search(query);      
  38.         System.out.println( " 查找\ " lighter\ "  共 "   +  hits.length()  +   " 个结果 " );      
  39.      
  40.         query  =  qp.parse( " javaeye " );      
  41.         hits  =  searcher.search(query);      
  42.         System.out.println( " 查找\ " javaeye\ "  共 "   +  hits.length()  +   " 个结果 " );      
  43.      
  44.     }       
  45.      
  46. }    
package  lighter.iteye.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)

一配合就行了
如:

Java代码 复制代码  收藏代码
  1. IndexWrtier indexWriter  =   new  IndexWriter(FSDirectory.getDirectory(“c:\\index”, true ), new  StandardAnlyazer(), true );   
  2. IndexWrtier indexWriter  =   new  IndexWriter( new  RAMDirectory(), new  StandardAnlyazer(), true );  
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)
将目录加进去
来看个例子:

Java代码 复制代码  收藏代码
  1. public   void  UniteIndex()  throws  IOException   
  2.     {   
  3.        IndexWriter writerDisk  =   new  IndexWriter(FSDirectory.getDirectory( " c:\\indexDisk " ,  true ), new  StandardAnalyzer(), true );   
  4.        Document docDisk  =   new  Document();   
  5.        docDisk.add( new  Field( " name " , " 程序员之家 " ,Field.Store.YES,Field.Index.TOKENIZED));   
  6.        writerDisk.addDocument(docDisk);   
  7.        RAMDirectory ramDir  =   new  RAMDirectory();   
  8.        IndexWriter writerRam  =   new  IndexWriter(ramDir, new  StandardAnalyzer(), true );   
  9.        Document docRam  =   new  Document();   
  10.        docRam.add( new  Field( " name " , " 程序员杂志 " ,Field.Store.YES,Field.Index.TOKENIZED));   
  11.        writerRam.addDocument(docRam);   
  12.        writerRam.close(); // 这个方法非常重要,是必须调用的    
  13.         writerDisk.addIndexes( new  Directory[] {ramDir} );   
  14.        writerDisk.close();   
  15.    }    
  16.     public   void  UniteSearch()  throws  ParseException, IOException   
  17.     {   
  18.        QueryParser queryParser  =   new  QueryParser( " name " , new  StandardAnalyzer());   
  19.        Query query  =  queryParser.parse( " 程序员 " );   
  20.        IndexSearcher indexSearcher  = new  IndexSearcher( " c:\\indexDisk " );   
  21.        Hits hits  =  indexSearcher.search(query);   
  22.        System.out.println( " 找到了 " + hits.length() + " 结果 " );   
  23.         for ( int  i = 0 ;i   
  24.         {   
  25.            Document doc  =  hits.doc(i);   
  26.            System.out.println(doc.get( " name " ));   
  27.        }    
 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 实例,究竟是什么类型的看分析器了。

拿以前的例子来说吧

Java代码 复制代码  收藏代码
  1. QueryParser queryParser  =   new  QueryParser( " name " , new  StandardAnalyzer());   
  2.         Query query  =  queryParser.parse( " 程序员 " );   
  3.  /* 这里返回的就是org.apache.lucene.search.PhraseQuery */    
  4.         IndexSearcher indexSearcher  = new  IndexSearcher( " c:\\indexDisk " );   
  5.         Hits hits  =  indexSearcher.search(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,new Sort(new SortField(String Field,SortComparatorSource)));
就看个例子吧:
这是一个建立索引的例子:

Java代码 复制代码  收藏代码
  1. public   void  IndexSort()  throws  IOException   
  2.  {   
  3.         IndexWriter writer  =   new  IndexWriter( " C:\\indexStore " , new  StandardAnalyzer(), true );   
  4.         Document doc  =   new  Document()   
  5.         doc.add( new  Field( " sort " , " 1 " ,Field.Store.YES,Field.Index.TOKENIZED));   
  6.         writer.addDocument(doc);   
  7.         doc  =   new  Document();   
  8.         doc.add( new  Field( " sort " , " 4 " ,Field.Store.YES,Field.Index.TOKENIZED));   
  9.         writer.addDocument(doc);   
  10.         doc  =   new  Document();   
  11.         doc.add( new  Field( " sort " , " 3 " ,Field.Store.YES,Field.Index.TOKENIZED));   
  12.         writer.addDocument(doc);   
  13.         doc  =   new  Document();   
  14.         doc.add( new  Field( " sort " , " 5 " ,Field.Store.YES,Field.Index.TOKENIZED));   
  15.         writer.addDocument(doc);   
  16.         doc  =   new  Document();   
  17.         doc.add( new  Field( " sort " , " 9 " ,Field.Store.YES,Field.Index.TOKENIZED));   
  18.         writer.addDocument(doc);   
  19.         doc  =   new  Document();   
  20.         doc.add( new  Field( " sort " , " 6 " ,Field.Store.YES,Field.Index.TOKENIZED));   
  21.         writer.addDocument(doc);   
  22.         doc  =   new  Document();   
  23.         doc.add( new  Field( " sort " , " 7 " ,Field.Store.YES,Field.Index.TOKENIZED));   
  24.         writer.addDocument(doc);   
  25.         writer.close();   
  26. }   
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();
} 



下面是搜索的例子:

Java代码 复制代码  收藏代码
  1. public void SearchSort1() throws IOException, ParseException   
  2. {   
  3.         IndexSearcher indexSearcher = new IndexSearcher("C:\\indexStore");   
  4.         QueryParser queryParser = new QueryParser("sort",new StandardAnalyzer());   
  5.         Query query = queryParser.parse("4");   
  6.           
  7.         Hits hits = indexSearcher.search(query);   
  8.         System.out.println("有"+hits.length()+"个结果");   
  9.         Document doc = hits.doc(0);   
  10.         System.out.println(doc.get("sort"));   
  11. }   
  12. public void SearchSort2() throws IOException, ParseException   
  13. {   
  14.         IndexSearcher indexSearcher = new IndexSearcher("C:\\indexStore");   
  15.         Query query = new RangeQuery(new Term("sort","1"),new Term("sort","9"),true);   
  16. //这个地方前面没有提到,它是用于范围的Query可以看一下帮助文档.   
  17.         Hits hits = indexSearcher.search(query,new Sort(new SortField("sort",new MySortComparatorSource())));   
  18.         System.out.println("有"+hits.length()+"个结果");   
  19.         for(int i=0;i   
  20.         {   
  21.             Document doc = hits.doc(i);   
  22.             System.out.println(doc.get("sort"));   
  23.         }   
  24. }   
  25. public class MyScoreDocComparator implements ScoreDocComparator   
  26. {   
  27.     private Integer[]sort;   
  28.     public MyScoreDocComparator(String s,IndexReader reader, String fieldname) throws IOException   
  29.     {   
  30.         sort = new Integer[reader.maxDoc()];   
  31.         for(int i = 0;i   
  32.         {   
  33.             Document doc =reader.document(i);   
  34.             sort[i]=new Integer(doc.get("sort"));   
  35.         }   
  36.     }   
  37.     public int compare(ScoreDoc i, ScoreDoc j)   
  38.     {   
  39.         if(sort[i.doc]>sort[j.doc])   
  40.             return 1;   
  41.         if(sort[i.doc]   
  42.             return -1;   
  43.         return 0;   
  44.     }   
  45.     public int sortType()   
  46.     {   
  47.         return SortField.INT;   
  48.     }   
  49.     public Comparable sortValue(ScoreDoc i)   
  50.     {   
  51.         // TODO 自动生成方法存根   
  52.         return new Integer(sort[i.doc]);   
  53.     }   
  54. }   
  55. public class MySortComparatorSource implements SortComparatorSource   
  56. {   
  57.     private static final long serialVersionUID = -9189690812107968361L;   
  58.     public ScoreDocComparator newComparator(IndexReader reader, String fieldname)   
  59.             throws IOException   
  60.     {   
  61.         if(fieldname.equals("sort"))   
  62.             return new MyScoreDocComparator("sort",reader,fieldname);   
  63.         return null;   
  64.     }   
  65. }  
public void SearchSort1() throws IOException, ParseException
{
        IndexSearcher indexSearcher = new IndexSearcher("C:\\indexStore");
        QueryParser queryParser = new QueryParser("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 = new IndexSearcher("C:\\indexStore");
        Query query = new RangeQuery(new Term("sort","1"),new Term("sort","9"),true);
//这个地方前面没有提到,它是用于范围的Query可以看一下帮助文档.
        Hits hits = indexSearcher.search(query,new Sort(new SortField("sort",new MySortComparatorSource())));
        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]=new Integer(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)
            throws IOException
    {
        if(fieldname.equals("sort"))
            return new MyScoreDocComparator("sort",reader,fieldname);
        return null;
    }
}



SearchSort1()输出的结果没有排序,SearchSort2()就排序了。
2.多域搜索MultiFieldQueryParser
如果想输入关键字而不想关心是在哪个Field里的就可以用MultiFieldQueryParser了
用它的构造函数即可后面的和一个Field一样。
MultiFieldQueryParser. parse(String[] queries, String[] fields, BooleanClause.Occur[] flags, Analyzer analyzer)                                          ~~~~~~~~~~~~~~~~~
第三个参数比较特殊这里也是与以前lucene1.4.3不一样的地方
看一个例子就知道了

Java代码 复制代码  收藏代码
  1. String[] fields = {"filename""contents""description"};   
  2.  BooleanClause.Occur[] flags = {BooleanClause.Occur.SHOULD,   
  3.                 BooleanClause.Occur.MUST,//在这个Field里必须出现的   
  4.                 BooleanClause.Occur.MUST_NOT};//在这个Field里不能出现   
  5.  MultiFieldQueryParser.parse("query", fields, flags, analyzer);  
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、默认的评分机制不太合理,需要根据自己的业务定制



整体来说lucene要用好不容易,必须在上述方面扩充他的功能,才能作为一个商用的搜索引擎

 

上传一份我个人认为比较好的API文档。。。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值