Lucene入门示例

主要参考了Lucene的官方示例  
环境:Win7 + JDK1.6 + Eclipse37 
Lucene版本:3.5 
官方: http://www.apache.org/dyn/closer.cgi  
检索的基本概念 
一 信息检索:从信息集合中打找出与用户相关的信息.  
1  信息检索的分类 
全文检索 :把用户的查询请求和全文中的每一个词进行比较不考虑查询请求与文本语义的匹配。 
数据检索 :查询要求和信息系统中的数据都有一定的结构,语义匹配能力差. 
知识检索 :强调基于知识语义上的匹配 
说明以下介绍来自于百科名片, http://baike.baidu.com/view/371811.htm  
二 Lucene介绍  
Lucene是apache软件基金会jakarta项目组的一个子项目,是一个开放源代码的全文检索引擎工具包,即它不是一个完整的全文检索引擎,而是一个全文检索引擎的架构,提供了完整的查询引擎和索引引擎.Lucene的原作者是Doug Cutting,他是一位资深全文索引/检索专家. 
优点如下: 
1 索引文件格式独立于应用平台。Lucene定义了一套以8位字节为基础的索引文件格式,使得兼容系统或者不同平台的应用能够共享建立的索引文件。、 
2 在传统全文检索引擎的倒排索引的基础上,实现了分块索引,能够针对新的文件建立小文件索引,提升索引速度。 
3 设计了独立于语言和文件格式的文本分析接口,索引器通过接受Token流完成索引文件的创立,用户扩展新的语言和文件格式,只需要实现文本分析的接口。 
4 Lucene的查询实现中默认实现了布尔操作、模糊查询(Fuzzy Search[11])、分组查询等. 
三 工程图片如下,所用jar文件包含:lucene-core-3.5.0.jar,lucene-analyzers-3.5.0.jar. 
 
四 想要搜索任何内容,必须先收集数据,建立索引库,之后才能进行搜索。 
具体实现类如下: 
Java代码   收藏代码
  1. package net.liuzd.lucene.test;  
  2.   
  3. import java.io.File;  
  4. import java.io.IOException;  
  5.   
  6. import org.apache.lucene.document.Document;  
  7. import org.apache.lucene.document.Field;  
  8. import org.apache.lucene.index.CorruptIndexException;  
  9. import org.apache.lucene.index.IndexWriter;  
  10. import org.apache.lucene.index.IndexWriterConfig;  
  11. import org.apache.lucene.index.IndexWriterConfig.OpenMode;  
  12. import org.apache.lucene.index.Term;  
  13. import org.apache.lucene.search.Filter;  
  14. import org.apache.lucene.search.IndexSearcher;  
  15. import org.apache.lucene.search.Query;  
  16. import org.apache.lucene.search.ScoreDoc;  
  17. import org.apache.lucene.search.TopDocs;  
  18. import org.junit.Test;  
  19.   
  20. public class IndeSearchFiles {  
  21.           
  22.     /** 
  23.      * 创建索引 
  24.      * @throws IOException  
  25.      * @throws CorruptIndexException  
  26.      * */  
  27.     @Test  
  28.     public void createIndex() throws Exception{  
  29.       
  30.         //操作增,删,改索引库的  
  31.         IndexWriter writer = LuceneUtils.createIndexWriter(OpenMode.CREATE);          
  32.         //数据源的位置  
  33.         File sourceFile = LuceneUtils.createSourceFile();  
  34.         System.out.println("文件路径:" + sourceFile.getAbsolutePath());  
  35.         //进行写入文档          
  36.         Document doc = new Document();  
  37.          doc.add(new Field("name",sourceFile.getName(),Field.Store.YES, Field.Index.ANALYZED_NO_NORMS));  
  38.         //文件路径  
  39.         Field pathField = new Field("path", sourceFile.getPath(), Field.Store.YES, Field.Index.NO);  
  40.         pathField.setIndexOptions(org.apache.lucene.index.FieldInfo.IndexOptions.DOCS_ONLY);  
  41.         doc.add(pathField);  
  42.         //文件最后修改时间  
  43.         doc.add(new Field("modified",String.valueOf(sourceFile.lastModified()),Field.Store.YES, Field.Index.NO));  
  44.         //添加文件内容  
  45.         String content = LuceneUtils.readFileContext(sourceFile);  
  46.         System.out.println("content: " + content);  
  47.         doc.add(new Field("contents",content,Field.Store.YES, Field.Index.ANALYZED));  
  48.         //以下是官网的实现  
  49.        /* FileInputStream fis = new FileInputStream(sourceFile); 
  50.         doc.add(new Field("contents", new BufferedReader(new InputStreamReader(fis, "UTF-8"))));*/  
  51.           
  52.         if (writer.getConfig().getOpenMode() == IndexWriterConfig.OpenMode.CREATE)  
  53.         {  
  54.            writer.addDocument(doc);  
  55.         }  
  56.         else  
  57.         {  
  58.           writer.updateDocument(new Term("path", sourceFile.getPath()), doc);  
  59.         }         
  60.         //释放资源  
  61.         writer.close();  
  62.        // fis.close();  
  63.           
  64.     }  
  65.       
  66.     /*** 
  67.      * 搜索 
  68.      * */  
  69.     @Test  
  70.     public void search() throws Exception{  
  71.           
  72.         //查询的字符串:输入不存在的字符串是查询不到的,如:中国  
  73.         String queryString = "Lucene";  
  74.         //查询字段集合  
  75.         String [] queryFileds = {"contents"};         
  76.         IndexSearcher searcher = LuceneUtils.createIndexSearcher();       
  77.         Query query = LuceneUtils.createQuery(queryFileds, queryString);  
  78.         //在搜索器中进行查询  
  79.         //对查询内容进行过滤  
  80.         Filter filter = null;  
  81.         //一次在索引器查询多少条数据  
  82.         int queryCount = 100;  
  83.         TopDocs results = searcher.search(query,filter,queryCount);  
  84.         System.out.println("总符合: " + results.totalHits + "条数!");  
  85.           
  86.         //显示记录  
  87.         for(ScoreDoc sr : results.scoreDocs){  
  88.             //文档编号  
  89.             int docID = sr.doc;  
  90.             //真正的内容  
  91.             Document doc = searcher.doc(docID);  
  92.             System.out.println("name = " + doc.get("name"));  
  93.             System.out.println("path = " + doc.get("path"));  
  94.             System.out.println("modified = " + doc.get("modified"));  
  95.             System.out.println("contents = " + doc.get("contents"));              
  96.         }         
  97.     }  
  98. }  

工具类代码如下: 
Java代码   收藏代码
  1. package net.liuzd.lucene.test;  
  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.   
  9. import org.apache.lucene.analysis.Analyzer;  
  10. import org.apache.lucene.analysis.standard.StandardAnalyzer;  
  11. import org.apache.lucene.index.CorruptIndexException;  
  12. import org.apache.lucene.index.IndexReader;  
  13. import org.apache.lucene.index.IndexWriter;  
  14. import org.apache.lucene.index.IndexWriterConfig;  
  15. import org.apache.lucene.index.IndexWriterConfig.OpenMode;  
  16. import org.apache.lucene.queryParser.MultiFieldQueryParser;  
  17. import org.apache.lucene.queryParser.ParseException;  
  18. import org.apache.lucene.queryParser.QueryParser;  
  19. import org.apache.lucene.search.IndexSearcher;  
  20. import org.apache.lucene.search.Query;  
  21. import org.apache.lucene.store.Directory;  
  22. import org.apache.lucene.store.FSDirectory;  
  23. import org.apache.lucene.util.Version;  
  24.   
  25. public class LuceneUtils {  
  26.   
  27.     //当前目录位置  
  28.     public static final String USERDIR = System.getProperty("user.dir");  
  29.     //存放索引的目录  
  30.     private static final String INDEXPATH = USERDIR + File.separator + "index";  
  31.     //数据源  
  32.     private static final String INDEXSOURCE = USERDIR + File.separator  
  33.             + "source" + File.separator + "lucene.txt";  
  34.     //使用版本  
  35.     public static final Version version = Version.LUCENE_35;  
  36.       
  37.     /** 
  38.      * 获取分词器 
  39.      * */  
  40.     public static Analyzer getAnalyzer(){  
  41.         // 分词器  
  42.         Analyzer analyzer = new StandardAnalyzer(version);  
  43.         return analyzer;  
  44.     }  
  45.   
  46.     /** 
  47.      * 创建一个索引器的操作类 
  48.      *  
  49.      * @param openMode 
  50.      * @return 
  51.      * @throws Exception 
  52.      */  
  53.     public static IndexWriter createIndexWriter(OpenMode openMode)  
  54.             throws Exception {  
  55.         // 索引存放位置设置  
  56.         Directory dir = FSDirectory.open(new File(INDEXPATH));        
  57.         // 索引配置类设置  
  58.         IndexWriterConfig iwc = new IndexWriterConfig(version,  
  59.                 getAnalyzer());  
  60.         iwc.setOpenMode(openMode);  
  61.         IndexWriter writer = new IndexWriter(dir, iwc);  
  62.         return writer;  
  63.     }  
  64.   
  65.     /*** 
  66.      * 创建一个搜索的索引器 
  67.      * @throws IOException  
  68.      * @throws CorruptIndexException  
  69.      * */  
  70.     public static IndexSearcher createIndexSearcher() throws CorruptIndexException, IOException {  
  71.         IndexReader reader = IndexReader.open(FSDirectory.open(new File(INDEXPATH)));  
  72.         IndexSearcher searcher = new IndexSearcher(reader);  
  73.         return searcher;  
  74.     }  
  75.   
  76.     /** 
  77.      * 创建一个查询器 
  78.      * @param queryFileds  在哪些字段上进行查询 
  79.      * @param queryString  查询内容 
  80.      * @return 
  81.      * @throws ParseException 
  82.      */  
  83.     public static Query createQuery(String [] queryFileds,String queryString) throws ParseException{  
  84.          QueryParser parser = new MultiFieldQueryParser(version, queryFileds, getAnalyzer());  
  85.          Query query = parser.parse(queryString);  
  86.          return query;  
  87.     }  
  88.       
  89.     /*** 
  90.      * 读取文件内容 
  91.      * */  
  92.     public static String readFileContext(File file){  
  93.         try {  
  94.             BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));  
  95.             StringBuilder content = new StringBuilder();  
  96.             for(String line = null; (line = br.readLine())!= null;){  
  97.                 content.append(line).append("\n");  
  98.             }  
  99.             return content.toString();  
  100.         } catch (Exception e) {  
  101.             throw new RuntimeException(e);  
  102.         }  
  103.       
  104.     }  
  105.       
  106.       
  107.     public static void main(String[] args) {  
  108.   
  109.         System.out.println(Thread.currentThread().getContextClassLoader()  
  110.                 .getResource(""));  
  111.         System.out.println(LuceneUtils.class.getClassLoader().getResource(""));  
  112.         System.out.println(ClassLoader.getSystemResource(""));  
  113.         System.out.println(LuceneUtils.class.getResource(""));  
  114.         System.out.println(LuceneUtils.class.getResource("/")); // Class文件所在路径  
  115.         System.out.println(new File("/").getAbsolutePath());  
  116.         System.out.println(System.getProperty("user.dir"));  
  117.     }  
  118.   
  119.     /** 
  120.      * 创建索引的数据源 
  121.      *  
  122.      * @return 
  123.      */  
  124.     public static File createSourceFile() {  
  125.         File file = new File(INDEXSOURCE);  
  126.         return file;  
  127.     }  
  128. }  

附件有工程源码与jar文件  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值