Lucene

Lucene首先要建立索引,才能进行搜索,使用了最新的lucene-4.2.1包

1.Indexer.java

[java]  view plain copy
  1. /** 
  2.  * 索引器 
  3.  * @author shishengjie 
  4.  * 
  5.  */  
  6. public class Indexer {  
  7.       
  8.     private IndexWriter writer;//写索引,负责创建索引或打开已有索引等等  
  9.   
  10.     public Indexer(String indexDir) throws IOException {  
  11.         //Directory描述索引存放的位置  
  12.         Directory dir = FSDirectory.open(new File(indexDir));  
  13.         //分析器,文本文件在被索引之前需要经过Analyzer处理  
  14.         Analyzer luceneAnalyzer = new StandardAnalyzer(Version.LUCENE_42);  
  15.         IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_42,  
  16.                 luceneAnalyzer);  
  17.         writer = new IndexWriter(dir, config);//创建写索引  
  18.   
  19.     }  
  20.   
  21.     public void close() throws IOException {  
  22.         writer.close();  
  23.     }  
  24.     /** 
  25.      * 文件过滤器 过滤所有非.txt文件 
  26.      * @author shishengjie 
  27.      * 
  28.      */  
  29.     private static class TextFilesFilter implements FileFilter {  
  30.   
  31.         @Override  
  32.         public boolean accept(File pathname) {  
  33.             // TODO Auto-generated method stub  
  34.             return pathname.getName().toLowerCase().endsWith(".txt");  
  35.         }  
  36.   
  37.     }  
  38.     /** 
  39.      * 建立索引 
  40.      * @param dataDir 
  41.      * @param filter 
  42.      * @return 
  43.      * @throws IOException 
  44.      */  
  45.     public int index(String dataDir, FileFilter filter) throws IOException {  
  46.         File files[] = new File(dataDir).listFiles();//索引文件夹下所有文件  
  47.         for (File f : files) {  
  48.             if (!f.isDirectory() && !f.isHidden() && f.exists() && f.canRead()  
  49.                     && (filter == null || filter.accept(f))) {  
  50.                 indexFile(f);//将文件加入所索引  
  51.             }  
  52.         }  
  53.         return writer.numDocs();  
  54.     }  
  55.   
  56.     /** 
  57.      * 向索引中添加文档 
  58.      * @param f 
  59.      * @throws IOException 
  60.      */  
  61.     private void indexFile(File f) throws IOException {  
  62.         System.out.println("Indexing " + f.getCanonicalPath());  
  63.         //根据文件名获取文档,Document代表一些域Filed的集合  
  64.         Document doc = getDocument(f);  
  65.         //加入到索引中  
  66.         writer.addDocument(doc);  
  67.     }  
  68.   
  69.     /** 
  70.      * 根据文件返回Document 
  71.      * @param f 
  72.      * @return 
  73.      * @throws IOException 
  74.      */  
  75.     private Document getDocument(File f) throws IOException {  
  76.         Document doc = new Document();//创建文档  
  77.         doc.add(new Field("contents"new FileReader(f)));  
  78.         doc.add(new Field("filename", f.getName(), Field.Store.YES,  
  79.                 Field.Index.NOT_ANALYZED));  
  80.         doc.add(new Field("fullpath", f.getCanonicalPath(), Field.Store.YES,  
  81.                 Field.Index.NOT_ANALYZED));//添加域Filed  
  82.         return doc;  
  83.     }  
  84.   
  85.     public static void main(String[] args) {  
  86.         try {  
  87.             if (args.length != 2) {  
  88.                 throw new IllegalAccessException("Usage:java "  
  89.                         + Indexer.class.getName() + " <index dir> <data dir>");  
  90.             }  
  91.   
  92.             String indexDir = args[0];  //此处存放索引文件  
  93.             String dataDir = args[1];   //对该文件夹下的文件建立索引  
  94.   
  95.             long start = System.currentTimeMillis();  
  96.             //创建索引,indexDir为索引存放位置  
  97.             Indexer indexer = new Indexer(indexDir);  
  98.             int numIndexed;  
  99.             try {  
  100.                 //对dataDir文件夹下的文件建立索引  
  101.                 numIndexed = indexer.index(dataDir, new TextFilesFilter());  
  102.             } finally {  
  103.                 indexer.close();  
  104.             }  
  105.             long end = System.currentTimeMillis();  
  106.             System.out.println("Indexing " + numIndexed + " files took "  
  107.                     + (end - start) + " milliseconds");  
  108.         } catch (Exception e) {  
  109.             e.printStackTrace();  
  110.         }  
  111.     }  
  112.   
  113. }  

运行时需要输入2个参数,第一个为要存放索引的文件夹,第二个为要索引哪个文件夹下的文件

如:C:\Users\shishengjie\Desktop\lucene\indexDir  C:\Users\shishengjie\Desktop\lucene\lucene-4.2.1\

将会扫描C:\Users\shishengjie\Desktop\lucene\lucene-4.2.1\文件夹下的txt文件,为其建立索引,创建的索引存放在C:\Users\shishengjie\Desktop\lucene\indexDir下面

输出为:

[plain]  view plain copy
  1. Indexing C:\Users\shishengjie\Desktop\lucene\lucene-4.2.1\CHANGES.txt  
  2. Indexing C:\Users\shishengjie\Desktop\lucene\lucene-4.2.1\JRE_VERSION_MIGRATION.txt  
  3. Indexing C:\Users\shishengjie\Desktop\lucene\lucene-4.2.1\LICENSE.txt  
  4. Indexing C:\Users\shishengjie\Desktop\lucene\lucene-4.2.1\MIGRATE.txt  
  5. Indexing C:\Users\shishengjie\Desktop\lucene\lucene-4.2.1\NOTICE.txt  
  6. Indexing C:\Users\shishengjie\Desktop\lucene\lucene-4.2.1\README.txt  
  7. Indexing C:\Users\shishengjie\Desktop\lucene\lucene-4.2.1\SYSTEM_REQUIREMENTS.txt  
  8. Indexing 21 files took 2479 milliseconds  


 


2.Searcher.java

[java]  view plain copy
  1. /** 
  2.  * 查找器 
  3.  * @author shishengjie 
  4.  * 
  5.  */  
  6. public class Searcher {  
  7.   
  8.     public static void main(String[] args) throws Exception {  
  9.   
  10.         if (args.length != 2) {  
  11.             throw new IllegalAccessException("Usage:java "  
  12.                     + Searcher.class.getName() + " <index dir> <data dir>");  
  13.         }  
  14.         String indexDir = args[0];//索引文件夹  
  15.         String q = args[1];//要检索的字符  
  16.         search(indexDir, q);//查找  
  17.     }  
  18.   
  19.     /** 
  20.      * 查找 
  21.      * @param indexDir 
  22.      * @param q 
  23.      * @throws Exception 
  24.      */  
  25.     private static void search(String indexDir, String q) throws Exception {  
  26.         //索引存放的位置处创建Directory  
  27.         Directory dir = FSDirectory.open(new File(indexDir));  
  28.         // 读取索引的indexReader  
  29.         IndexReader indexReader = IndexReader.open(dir);  
  30.         // 创建indexSearcher,用于搜索由IndexWriter类创建的索引  
  31.         IndexSearcher is = new IndexSearcher(indexReader);  
  32.         //解析查询字符串  
  33.         QueryParser parser = new QueryParser(Version.LUCENE_42, "contents",  
  34.                 new StandardAnalyzer(Version.LUCENE_42));  
  35.         //将人可读的查询解析为Query  
  36.         Query query = parser.parse(q);  
  37.         long start = System.currentTimeMillis();  
  38.         //查询,以TopDocs对象的形式返回搜索结果集  
  39.         //TopDocs是一个简单的指针容器,指向前N个排名的搜索结果  
  40.         //TopDocs只包括对于文档的引用IndexSearcher.doc时才加载  
  41.         TopDocs hits = is.search(query, 10);  
  42.         long end = System.currentTimeMillis();  
  43.         System.err.println("Found " + hits.totalHits + " document(s) (in "  
  44.                 + +(end - start) + " milliseconds) that matched query '" + q  
  45.                 + "'");  
  46.         //输出匹配的文本  
  47.         for (ScoreDoc scoreDoc : hits.scoreDocs) {  
  48.             Document doc = is.doc(scoreDoc.doc);//返回匹配文本  
  49.             System.out.println(doc.get("fullpath"));  
  50.         }  
  51.   
  52.     }  
  53.   
  54. }  


运行时需要输入2个参数,第一个为要存放索引的文件夹,第二个为要查询的单词

如:C:\Users\shishengjie\Desktop\lucene\indexDir  patent

将会读取索引,查找patent文件

输出为:

[plain]  view plain copy
  1. Found 6 document(s) (in 191 milliseconds) that matched query 'java'  
  2. C:\Users\shishengjie\Desktop\lucene\lucene-4.2.1\JRE_VERSION_MIGRATION.txt  
  3. C:\Users\shishengjie\Desktop\lucene\lucene-4.2.1\SYSTEM_REQUIREMENTS.txt  
  4. C:\Users\shishengjie\Desktop\lucene\lucene-4.2.1\README.txt  
  5. C:\Users\shishengjie\Desktop\lucene\lucene-4.2.1\NOTICE.txt  
  6. C:\Users\shishengjie\Desktop\lucene\lucene-4.2.1\LICENSE.txt  
  7. C:\Users\shishengjie\Desktop\lucene\lucene-4.2.1\CHANGES.txt  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值