Java学习者论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

手机号码,快捷登录

恭喜Java学习者论坛(https://www.javaxxz.com)已经为数万Java学习者服务超过8年了!积累会员资料超过10000G+
成为本站VIP会员,下载本站10000G+会员资源,购买链接:点击进入购买VIP会员
JAVA高级面试进阶视频教程Java架构师系统进阶VIP课程

分布式高可用全栈开发微服务教程

Go语言视频零基础入门到精通

Java架构师3期(课件+源码)

Java开发全终端实战租房项目视频教程

SpringBoot2.X入门到高级使用教程

大数据培训第六期全套视频教程

深度学习(CNN RNN GAN)算法原理

Java亿级流量电商系统视频教程

互联网架构师视频教程

年薪50万Spark2.0从入门到精通

年薪50万!人工智能学习路线教程

年薪50万!大数据从入门到精通学习路线年薪50万!机器学习入门到精通视频教程
仿小米商城类app和小程序视频教程深度学习数据分析基础到实战最新黑马javaEE2.1就业课程从 0到JVM实战高手教程 MySQL入门到精通教程
查看: 370|回复: 0

[Java框架学习]lucene入门实例(1):索引文本文件

[复制链接]
  • TA的每日心情
    开心
    2021-3-12 23:18
  • 签到天数: 2 天

    [LV.1]初来乍到

    发表于 2014-11-4 00:00:37 | 显示全部楼层 |阅读模式
    Lucene是apache组织的一个用java实现全文搜索引擎的开源项目。 其功能非常的强大,api也很简单。总得来说用Lucene来进行建立 和搜索和操作数据库是差不多的(有点像),Document可以看作是 数据库的一行记录,Field可以看作是数据库的字段。用lucene实 现搜索引擎就像用JDBC实现连接数据库一样简单。  Lucene3.0是最新版本 Lucene3.0的下载地址是http://apache.justdn.org/lucene/java/

    本文使用Lucene2.2.
    例子一 :

    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.isFile()   
                         &&  textFiles.getName().endsWith( " .txt " ))   {   
                     System.out.println( " File  "   +  textFiles.getCanonicalPath()   
                              +   " 正在被索引.... " );   
                     String temp  =  FileReaderAll(textFiles.getCanonicalPath(),   
                              " GBK " );   
                     System.out.println(temp);   
                     Document document  =   new  Document();   
                     Field FieldPath  =   new  Field( " path " , textFiles.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"等单词,也删除了所有的标点
    查看一下结果与"new StringReader("lighter javaeye com is the are on")"作一个比较就清楚明了。
    这里不对其API进行解释了,具体见lucene的官方文档。需要注意一点,这里的代码使用的是lucene2的API  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可以设置各个关键字之间的关系这个是最常用的了。


      

      
    1、lucene的索引不能太大,要不然效率会很低。大于1G的时候就必须考虑分布索引的问题
       2、不建议用多线程来建索引,产生的互锁问题很麻烦。经常发现索引被lock,无法重新建立的情况 3、中文分词是个大问题,目前免费的分词效果都很差。如果有能力还是自己实现一个分词模块,用最短路径的切分方法,网上有教材和demo源码,可以参考。 4、建增量索引的时候很耗cpu,在访问量大的时候会导致cpu的idle为0 5、默认的评分机制不太合理,需要根据自己的业务定制 整体来说lucene要用好不容易,必须在上述方面扩充他的功能,才能作为一个商用的搜索引擎

      
      
       
       

         
       

         
       
      
    复制代码

    源码下载:http://file.javaxxz.com/2014/11/4/000036546.zip
    回复

    使用道具 举报

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    QQ|手机版|Java学习者论坛 ( 声明:本站资料整理自互联网,用于Java学习者交流学习使用,对资料版权不负任何法律责任,若有侵权请及时联系客服屏蔽删除 )

    GMT+8, 2025-2-25 14:05 , Processed in 0.301972 second(s), 36 queries .

    Powered by Discuz! X3.4

    © 2001-2017 Comsenz Inc.

    快速回复 返回顶部 返回列表