全文检索之lucene入门篇HelloWorld

首先,先看下目录结构。


       第一步,在eclipse中建立jave项目。需要引入jar包,只有3个,分别是lucene的分词器和核心包,还有高亮显示器。做法是建立一个lib文件夹,将jar包拷过来,然后右击,选择Build Path(构建路径),Addto Build Path(添加到项目的构建路径)。


          然后建立datasource文件夹,添几个txt的文件进去,内容爱写啥写啥。(但是建议是一个是中文,一个是英文,可以测两种语言的分词)。还有luceneIndex文件夹,用来存放创建的索引.

         其中,IndexWriteraddDocument's a javadoc.txt的内容是

Adds room adocument to this room index. If the room document contains room  more than setMaxFieldLength(int) terms for agiven field, the remainder are discarded.

         小笑话_总统的房间 Room .txt 的内容是

总统的房间

    一位绅士到旅游胜地的一家饭店要开个房间,

    侍者因为他没有预定而拒绝说:“房间全满,无法安排。”

    “听着!”绅士说,“假如我告诉你总统要到这里来,你一定会马上向他提供一套客房吧?”

    “当然啦,他是总……”

    “好了,我荣幸地通知你:总统今晚不来了。你把他的房间给我吧!”

          然后建立包,com.lucene.helloworld,新建一个HelloWorld的类。里面主要的两个方法就是建立索引,以及查询关键字。

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package com.lucene.helloworld;  
  2.   
  3. import org.apache.lucene.analysis.Analyzer;  
  4. import org.apache.lucene.analysis.standard.StandardAnalyzer;  
  5. import org.apache.lucene.document.Document;  
  6. import org.apache.lucene.index.IndexWriter;  
  7. import org.apache.lucene.index.IndexWriter.MaxFieldLength;  
  8. import org.apache.lucene.queryParser.MultiFieldQueryParser;  
  9. import org.apache.lucene.queryParser.QueryParser;  
  10. import org.apache.lucene.search.Filter;  
  11. import org.apache.lucene.search.IndexSearcher;  
  12. import org.apache.lucene.search.Query;  
  13. import org.apache.lucene.search.ScoreDoc;  
  14. import org.apache.lucene.search.TopDocs;  
  15. import org.junit.Test;  
  16.   
  17. import com.lucene.units.File2DocumentUtils;  
  18.   
  19. public class HelloWorld {  
  20.     //需要查询的文件所在的路径    
  21.     String filePath = "F:\\Users\\liuyanling\\workspace\\LuceneDemo\\datasource\\peoplewhocannot.txt";  
  22.     //设置索引存放的路径  
  23.     String indexPath = "F:\\Users\\liuyanling\\workspace\\LuceneDemo\\luceneIndex";  
  24.     //设置分词器为标准分词器  
  25.     Analyzer analyzer = new StandardAnalyzer();  
  26.       
  27.     /** 
  28.      * 创建索引,先将文件File转化为Document类型,然后用IndexWriter,将Document按照设定的分词器和其他规则,创建索引,存到相应路径中 
  29.      */  
  30.     @Test  
  31.     public void createIndex() throws Exception {  
  32.         Document doc = File2DocumentUtils.file2Document(filePath);  
  33.           
  34.         IndexWriter indexWriter = new IndexWriter(indexPath,analyzer,true,MaxFieldLength.LIMITED);  
  35.         indexWriter.addDocument(doc);  
  36.           
  37.         indexWriter.close();  
  38.     }  
  39.       
  40.     /** 
  41.      * 搜索,查询关键字queryString,先设置查询的范围,在"名称"和"内容"中查询。然后用IndexSearcher来查询, 
  42.      * 通过查询索引来将结果返回。返回的结果是TopDocs类型,还需要进行处理才能拿到结果。 
  43.      */  
  44.     @Test  
  45.     public void search() throws Exception {  
  46.         String queryString = "Internet";  
  47.           
  48.         String[] fields = {"name","content"};  
  49.         QueryParser queryParser = new MultiFieldQueryParser(fields,analyzer);  
  50.         Query query = queryParser.parse(queryString);  
  51.           
  52.         IndexSearcher indexSearcher = new IndexSearcher(indexPath);  
  53.         Filter filter = null;  
  54.         //查询前10000条记录  
  55.         TopDocs topDocs = indexSearcher.search(query,filter,10000);  
  56.           
  57.         System.out.println("总共有["+topDocs.totalHits+"]条匹配结果");  
  58.           
  59.         //将查询出的结果的scoreDocs进行遍历  
  60.         for (ScoreDoc scoreDoc : topDocs.scoreDocs ) {  
  61.             //取出文件的doc编号  
  62.             int docSn = scoreDoc.doc;   
  63.             //根据编号,用indexSearcher查找到document文件  
  64.             Document doc = indexSearcher.doc(docSn);  
  65.             //将Document文件内容打印出来  
  66.             File2DocumentUtils.printDocumentInfo(doc);  
  67.         };  
  68.     }  
  69. }  

     接着,由于里面用了File2DocumentUtils类的printDocumentInfo()file2Document(),打印Document内容和File转换为Document两个方法。看看File2DocummentUtils文件内容.

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package com.lucene.units;  
  2.   
  3. import java.io.BufferedReader;  
  4. import java.io.File;  
  5. import java.io.FileInputStream;  
  6. import java.io.FileNotFoundException;  
  7. import java.io.InputStreamReader;  
  8.   
  9. import org.apache.lucene.document.Document;  
  10. import org.apache.lucene.document.Field;  
  11. import org.apache.lucene.document.NumberTools;  
  12. import org.apache.lucene.document.Field.Index;  
  13. import org.apache.lucene.document.Field.Store;  
  14.   
  15. /** 
  16.  * File转化为Document的工具类 
  17.  * @author liuyanling 
  18.  * 
  19.  */  
  20. public class File2DocumentUtils {  
  21.       
  22.     /** 
  23.      * 文件File转为Document.先根据路径,读取出File文件.然后根据文件的Name,content,size,path来建立索引,确认是否存储. 
  24.      * @param path 
  25.      * @return Document,被转换好的结果 
  26.      */  
  27.     public static Document file2Document(String path) {  
  28.         File file = new File(path);  
  29.           
  30.         Document doc = new Document();  
  31.         //将文件名和内容分词,建立索引,存储;而内容通过readFileContent方法读取出来。  
  32.         doc.add(new Field("name",file.getName(),Store.YES,Index.ANALYZED));  
  33.         doc.add(new Field("content",readFileContent(file),Store.YES,Index.ANALYZED));  
  34.         //将文件大小存储,但建立索引,但不分词;路径则不需要建立索引  
  35.         doc.add(new Field("size",String.valueOf(file.length()),Store.YES,Index.NOT_ANALYZED));  
  36.         doc.add(new Field("path",file.getPath(),Store.YES,Index.NO));  
  37.           
  38.         return doc;  
  39.           
  40.     }  
  41.       
  42.     /** 
  43.      * 读取文件内容。通过FileInputStream文件输入流,InputStreamReader读取输入流,再用BufferedReader包装,可以readLine 
  44.      * 一行一行将数据取出。 
  45.      * @param file 文件对象 
  46.      * @return String,文件中的内容 
  47.      */  
  48.     public static String readFileContent(File file) {  
  49.         try {  
  50.             BufferedReader reader = new BufferedReader (new InputStreamReader(new FileInputStream(file)));  
  51.             //存储File的内容  
  52.             StringBuffer content = new StringBuffer();  
  53.               
  54.             for(String line = null;(line = reader.readLine()) != null;) {  
  55.                 content.append(line).append("\n");  
  56.             }  
  57.               
  58.             return content.toString();  
  59.                   
  60.         } catch (Exception e) {  
  61.             throw new RuntimeException();  
  62.         }  
  63.     }  
  64.       
  65.     /** 
  66.      * 将Document文件的内容打印出来,直接根据之前建立索引的使用的字段名,get出字段内容,打印 
  67.      * @param doc 
  68.      */  
  69.     public static void printDocumentInfo(Document doc) {  
  70. //      //第一种读取方式,先getfiled,然后stringValue  
  71. //      Field r = doc.getField("name");  
  72. //      r.stringValue();  
  73.           
  74.         //第二种读取方式,直接get  
  75.         System.out.println("name ="+doc.get("name"));  
  76.         System.out.println("content =" +doc.get("content"));  
  77.         System.out.println("size =" +doc.get("size"));  
  78.         System.out.println("path =" +doc.get("path"));  
  79.     }  
  80.  }  

    代码写完了,先创建索引,在createIndex方法上右击Run As选择Junit Test,进行单元测试


    测试成功之后,就可以看到index增加了,说明索引添加了。


    然后测试测试,查询的结果如下。只查询到一个结果,将namecontextsize和路径都打印出来了。


          以上就是简单的全文检索查询,缺陷有很多,比如索引的存放位置是事先手动创建的,比如没有进行查询结果的高亮设置,比如对于分词器也只使用了标准的分词器。所以,改进请见下篇《全文检索之 lucene 的优化篇 -- 创建索引存放的目录》.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值