Lucene3.4入门示例
评论(0) 浏览量(11357)

原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 、作者信息和本声明。否则将追究法律责任。http://enetq.blog.51cto.com/479739/697704

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.     @Test 
  30.     public void creatIndex() throws Exception {  
  31.         // file-->Document  
  32.         Document doc = File2Document.file2Document(filePath);  
  33.         //Directory dir = FSDirectory.open(indexPath);   
  34.         IndexWriter indexWriter = new IndexWriter(FSDirectory.open(indexPath), analyzer, true,MaxFieldLength.LIMITED);  
  35.         indexWriter.addDocument(doc);  
  36.         indexWriter.close();  
  37.  
  38.     }  
  39.    
  40.  
  41.      
  42.     @Test 
  43.     public void search() throws Exception {  
  44.         String queryString = "搜索";  
  45.         //把要搜索的文本解析为Query  
  46.         String[] fields = {"name","content"};  
  47.         QueryParser queryParser = new MultiFieldQueryParser(Version.LUCENE_34, fields, analyzer); //查询解析器  
  48.         Query query = queryParser.parse(queryString);  
  49.         //查询  
  50.         IndexSearcher indexSearcher = new IndexSearcher(FSDirectory.open(indexPath));  
  51.         Filter filter = null;  
  52.         TopDocs topDocs = indexSearcher.search(query, filter, 10000);//topDocs 类似集合  
  53.         System.out.println("总共有【"+topDocs.totalHits+"】条匹配结果.");  
  54.         //输出      
  55.             for(ScoreDoc scoreDoc:topDocs.scoreDocs){  
  56.             int docSn = scoreDoc.doc;//文档内部编号  
  57.             Document doc = indexSearcher.doc(docSn);//根据文档编号取出相应的文档  
  58.             File2Document.printDocumentInfo(doc);//打印出文档信息  
  59.               
  60.         }  
  61.  
  62.     }  
  63.  
  64.  
  65.  
  66.  
  67. }  

 

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.     private static String readFileContent(File file) {  
  30.         try {  
  31.             BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));  
  32.             StringBuffer content = new StringBuffer();  
  33.             try {  
  34.                 for(String line=null;(line = reader.readLine())!=null;){  
  35.                     content.append(line).append("\n");  
  36.                 }  
  37.             } catch (IOException e) {  
  38.                    
  39.                 e.printStackTrace();  
  40.             }  
  41.             return content.toString();  
  42.         } catch (FileNotFoundException e) {  
  43.                
  44.             e.printStackTrace();  
  45.         }  
  46.         return null;  
  47.     }  
  48.      
  49.     public static void printDocumentInfo(Document doc){  
  50.         System.out.println("name -->"+doc.get("name"));  
  51.         System.out.println("content -->"+doc.get("content"));  
  52.         System.out.println("path -->"+doc.get("path"));  
  53.         System.out.println("size -->"+doc.get("size"));  
  54.           
  55.     }  
  56.  
  57. }  

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】条匹配结果.  

本文出自 “幽灵柯南的技术blog” 博客,请务必保留此出处http://enetq.blog.51cto.com/479739/697704

没有登录不能评论