Lucene3.4入门示例一

Lucene3.4 下载地址:http://lucene.apache.org/ 14 September 2011

简介如下:(官网简介:)

 
 
  1. What Is Apache Lucene?  
  2. The Apache Lucene™ project develops open-source search software, including:   
  3.  
  4. Apache Lucene Core™ (formerly named Lucene Java), our flagship sub-project, provides a Java-based indexing and search implementation, as well as spellchecking, hit highlighting and advanced analysis/tokenization capabilities.   
  5. Apache Solr™ is our high performance enterprise search server, with XML/HTTP and JSON/Python/Ruby APIs, hit highlighting, faceted search, caching, replication, distributed search, database integration, web admin and search interfaces.   
  6. Apache PyLucene™ is a Python port of the the Lucene Core project.   
  7. Apache Open Relevance Project™ is a subproject with the aim of collecting and distributing free materials for relevance testing and performance.   

示例:本示例要实现的功能是:查找txt文本文档中的关键字,如果找到,则显示匹配结果,并输出文件名、存放路径、大小、内容.

原理:采集建立索引,从信息源中拷贝到本地进行加工处理,这里的信息源可以是数据库、互联网等,存入索引库(一组文件的集合,二进制).搜索时从本地的信息集合中进行搜索.文本信息在建立索引和搜索时,都会使用到分词器进行分词,并且使用的是同一个分词器.索引库可以理解为包含索引表和索引表对应的数据、文档等的集合.搜索时,分词器对关键字进行处理,比照索引表,通过索引表找到数据。

示例实战:

建立测试hello.txt文件内容如下:

 
 
  1. hello1 world test for fd. document document  
  2. Just a case; hel  
  3. hello是 测试测试搜索 1 hrllo hello hello hello 

1.建立一个Java Project

2.导入Lucene3.4 必须jar包

lucene-core-3.4.0.jar//核心jar包

contrib\highlighter\lucene-highlighter-3.4.0.jar //高亮

contrib\analyzers\lucene-analyzers-3.4.0.jar //分词器

新建数据源(本地)文件夹luceneDataSource,索引文件夹luceneIndex

3.LuceneDemo.java源代码:

 
 
  1. import java.io.File;  
  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.  
  9. import org.apache.lucene.queryParser.MultiFieldQueryParser;  
  10. import org.apache.lucene.queryParser.QueryParser;  
  11. import org.apache.lucene.search.Filter;  
  12. import org.apache.lucene.search.IndexSearcher;  
  13. import org.apache.lucene.search.Query;  
  14. import org.apache.lucene.search.ScoreDoc;  
  15. import org.apache.lucene.search.TopDocs;  
  16. import org.apache.lucene.store.FSDirectory;  
  17. import org.apache.lucene.util.Version;  
  18. import org.junit.Test;  
  19.  
  20. import com.yaxing.utils.File2Document;  
  21.    
  22. public class LuceneDemo {  
  23.     String filePath = "J:\\MyEclipse-8.6\\lucene\\LuceneDemo\\luceneDataSource\\hello.txt";  
  24.     File indexPath = new File("J:\\MyEclipse-8.6\\lucene\\LuceneDemo\\luceneIndex");  
  25.     Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_34);  
  26.       
  27.  
  28.     /**  
  29.      * 建立索引 IndexWriter 增、删、改  
  30.      * */ 
  31.     @Test 
  32.     public void creatIndex() throws Exception {  
  33.         // file-->Document  
  34.         Document doc = File2Document.file2Document(filePath);  
  35.         //Directory dir = FSDirectory.open(indexPath);   
  36.         IndexWriter indexWriter = new IndexWriter(FSDirectory.open(indexPath), analyzer, true,MaxFieldLength.LIMITED);  
  37.         indexWriter.addDocument(doc);  
  38.         indexWriter.close();  
  39.  
  40.     }  
  41.    
  42.  
  43.     /**  
  44.      * 搜索 IndexSearcher   
  45.      * 用来在索引库中进行查询  
  46.      * */ 
  47.     @Test 
  48.     public void search() throws Exception {  
  49.         String queryString = "搜索";  
  50.         //把要搜索的文本解析为Query  
  51.         String[] fields = {"name","content"};  
  52.         QueryParser queryParser = new MultiFieldQueryParser(Version.LUCENE_34, fields, analyzer); //查询解析器  
  53.         Query query = queryParser.parse(queryString);  
  54.         //查询  
  55.         IndexSearcher indexSearcher = new IndexSearcher(FSDirectory.open(indexPath));  
  56.         Filter filter = null;  
  57.         TopDocs topDocs = indexSearcher.search(query, filter, 10000);//topDocs 类似集合  
  58.         System.out.println("总共有【"+topDocs.totalHits+"】条匹配结果.");  
  59.         //输出      
  60.             for(ScoreDoc scoreDoc:topDocs.scoreDocs){  
  61.             int docSn = scoreDoc.doc;//文档内部编号  
  62.             Document doc = indexSearcher.doc(docSn);//根据文档编号取出相应的文档  
  63.             File2Document.printDocumentInfo(doc);//打印出文档信息  
  64.               
  65.         }  
  66.  
  67.     }  
  68.  
  69.  
  70.  
  71.  
  72. }  

 

4.File2Document.java源码

 

 
 
  1.  
  2. import java.io.BufferedReader;  
  3. import java.io.File;  
  4. import java.io.FileInputStream;  
  5. import java.io.FileNotFoundException;  
  6. import java.io.IOException;  
  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.Field.Index;  
  12. import org.apache.lucene.document.Field.Store;  
  13.  
  14. public class File2Document {  
  15.     //文件属性: content,name,size,path  
  16.     public static Document file2Document(String path){  
  17.         File file = new File(path);  
  18.         Document doc = new Document();  
  19.         //Store.YES 是否存储 yes no compress   
  20.         //Index 是否进行索引 Index.ANALYZED 分词后进行索引  
  21.         doc.add(new Field("name",file.getName(),Store.YES,Index.ANALYZED));       
  22.         doc.add(new Field("content",readFileContent(file),Store.YES,Index.ANALYZED));//readFileContent()读取文件类容        
  23.         doc.add(new Field("size",String.valueOf(file.length()),Store.YES,Index.NOT_ANALYZED));//不分词,文件大小(int)转换成String         
  24.         doc.add(new Field("path",file.getAbsolutePath(),Store.YES,Index.NOT_ANALYZED));//不需要根据文件的路径来查询    
  25.         return doc;  
  26.     }  
  27.     /**  
  28.      * 读取文件类容  
  29.      * */ 
  30.  
  31.     private static String readFileContent(File file) {  
  32.         try {  
  33.             BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));  
  34.             StringBuffer content = new StringBuffer();  
  35.             try {  
  36.                 for(String line=null;(line = reader.readLine())!=null;){  
  37.                     content.append(line).append("\n");  
  38.                 }  
  39.             } catch (IOException e) {  
  40.                    
  41.                 e.printStackTrace();  
  42.             }  
  43.             return content.toString();  
  44.         } catch (FileNotFoundException e) {  
  45.                
  46.             e.printStackTrace();  
  47.         }  
  48.         return null;  
  49.     }  
  50.     /**  
  51.      * <pre>  
  52.      * 获取name属性值的两种方法  
  53.      * 1.Filed field = doc.getFiled("name");  
  54.      *         field.stringValue();  
  55.      * 2.doc.get("name");  
  56.      * </pre>  
  57.      * @param doc  
  58.      * */ 
  59.     public static void printDocumentInfo(Document doc){  
  60.         System.out.println("name -->"+doc.get("name"));  
  61.         System.out.println("content -->"+doc.get("content"));  
  62.         System.out.println("path -->"+doc.get("path"));  
  63.         System.out.println("size -->"+doc.get("size"));  
  64.           
  65.     }  
  66.  
  67. }  

5.Junit测试结果:

String queryString = "搜索";  

 
 
  1. 总共有【1】条匹配结果.  
  2. name -->hello.txt  
  3. content -->hello1 world test for fd. document document  
  4. Just a case; hel  
  5. hello是 测试测试搜索 1 hrllo hello hello hello  
  6.  
  7. path -->J:\MyEclipse-8.6\lucene\LuceneDemo\luceneDataSource\hello.txt  
  8. size -->109  

String queryString = "hello";  

 
 
  1. 总共有【1】条匹配结果.  
  2. name -->hello.txt  
  3. content -->hello1 world test for fd. document document  
  4. Just a case; hel  
  5. hello是 测试测试搜索 1 hrllo hello hello hello  
  6.  
  7. path -->J:\MyEclipse-8.6\lucene\LuceneDemo\luceneDataSource\hello.txt  
  8. size -->109 

 

 

索引建立如下:

 

 

 

String queryString = "zazazaza";

 

 
 
  1. 总共有【0】条匹配结果.  

本文转自 w156445045 51CTO博客,原文链接:http://blog.51cto.com/enetq/697704 ,如需转载请自行联系原作者
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值