Lucene介绍和实战

来源:互联网 发布:java程序员等级划分 编辑:程序博客网 时间:2024/06/06 10:57

前言

给你一张过去的CD,听听我们有过的思绪~~~~~

Lucene简介

Lucene是一个开源的、成熟的java检索库。它为许多文档(Document)维护了一个倒排索引表,并且向外表现出了简单易用的API。更多有关Lucene的介绍可以参看Lucene的百科。

下图展现了Lucene的索引处理和检索处理的流程(点击图片放大):

下面的表格描述了Lucene中各包的作用。

包   名

功   能

org.apache.lucene.analysis

语言分析器,主要用于切词,中文切词可以扩展此类

org.apache.lucene.document

索引存储时的文档结构管理,类似于关系型数据库的表结构

org.apache.lucene.index

索引管理,包括索引建立、删除等

org.apache.lucene.queryParser

查询分析器,实现查询关键词的运算,如与、或、非等

org.apache.lucene.search

检索管理,根据查询条件,检索得到结果

org.apache.lucene.store

数据存储管理,主要包括一些底层的I/O操作

org.apache.lucene.util

一些公用类

Lucene入门应用

上图中,红色部分是我们需要利用Lucene的API来进行干涉的,不过这些都非常容易。下面是利用Lucene实现全文检索功能的一般步骤(未整合任何框架):

  • 创建索引
[java] view plain copy
  1. package org.xiaom.lucene;  
  2.   
  3. import java.io.BufferedReader;  
  4.   
  5. public class MyIndexCreater {  
  6.     private static IndexWriter indexWriter;  
  7.     private static Version version = Version.LUCENE_35;  
  8.     /** 
  9.      * 为该目录<strong>及其子目录</strong>下所有的文本文件(.java;.xml;.txt)创建索引 
  10.      * @param docPath 文档存放路径 
  11.      * @param indexPath 索引存放路径 
  12.      */  
  13.     public static void createContainChild(String docPath, String indexPath)  
  14.             throws IOException {  
  15.         File docDir = new File(docPath);  
  16.         File indexDir = new File(indexPath);  
  17.         //1,打开索引的存放目录  
  18.         Directory directory = FSDirectory.open(indexDir);  
  19.         //2,创建IndexWriterConfig  
  20.         IndexWriterConfig conf = new IndexWriterConfig(version,new StandardAnalyzer(version));  
  21.         //每次都覆盖之前的索引文件  
  22.         conf.setOpenMode(OpenMode.CREATE);  
  23.         //根据IndexWriterConfig实例创建IndexWriter  
  24.         indexWriter = new IndexWriter(directory, conf);  
  25.           
  26.         indexDir(docDir);  
  27.         //7,提交,关闭indexWrtier(必须)  
  28.         indexWriter.commit();  
  29.         indexWriter.close();  
  30.     }  
  31.     // 该目录及其子目录创建索引,返回索引文件总数  
  32.     private static int indexDir(File dir) {  
  33.         int c = 0;  
  34.         File[] files = dir.listFiles();  
  35.         for (File f : files) {  
  36.             if (f.isDirectory()) {  
  37.                 indexDir(f);  
  38.             } else if (f.getName().endsWith(".java")  
  39.                     || f.getName().endsWith(".txt")  
  40.                     || f.getName().endsWith(".xml")) {  
  41.                 c += indexFile(f);  
  42.             }  
  43.         }  
  44.         return c;  
  45.     }  
  46.     //为某个文件创建索引,索引成功返回1,失败0  
  47.     private static int indexFile(File f) {  
  48.         boolean rs = true;  
  49.         BufferedReader br = null;  
  50.         String titleStr = null;  
  51.         StringBuffer contentStr = new StringBuffer();  
  52.         try {  
  53.             br = new BufferedReader(new FileReader(f));  
  54.             titleStr = br.readLine();  
  55.             String s;  
  56.             while((s=br.readLine())!=null){  
  57.                 contentStr.append(s);  
  58.                 contentStr.append("\n");  
  59.             }  
  60.             //3,创建Document对象  
  61.             Document doc = new Document();  
  62.             //4,创建Field对象  
  63.             Field name = new Field("name", f.getName(), Store.YES, Index.ANALYZED);  
  64.             Field title = new Field("title", titleStr, Store.YES, Index.ANALYZED);  
  65.             Field content = new Field("content", contentStr.toString(), Store.YES,Index.ANALYZED);  
  66.             //5,将Field对象加入到Document  
  67.             doc.add(name);  
  68.             doc.add(title);  
  69.             doc.add(content);  
  70.             //6,将Document加入到indexWriter  
  71.             indexWriter.addDocument(doc);  
  72.         } catch (Exception e) {  
  73.             e.printStackTrace();  
  74.             rs = false;  
  75.         }  
  76.         return rs ? 1 : 0;  
  77.     }  
  78. }  
  • 搜索
[java] view plain copy
  1. package org.xiaom.lucene;  
  2.   
  3. import java.io.File;  
  4.   
  5. public class MyIndexSearcher {  
  6.     private static Version version=Version.LUCENE_35;  
  7.     /** 
  8.      * @param indexPath 索引存放路径 
  9.      * @param key 搜索关键字 
  10.      * @param value 关键字的值 
  11.      */  
  12.     public static void search(String indexPath, String key, String value) {  
  13.         IndexReader ireader = null;  
  14.         try {  
  15.             //1,创建IndexReader  
  16.             ireader = IndexReader.open(FSDirectory.open(new File(indexPath)));  
  17.             //2,根据indexReader实例创建IndexSearcher  
  18.             IndexSearcher indexSearcher = new IndexSearcher(ireader);  
  19.             //3,创建QueryParser  
  20.             QueryParser queryParser =new QueryParser(version,key,new StandardAnalyzer(version));  
  21.             //4,通过queryParser解析出Query  
  22.             Query query=queryParser.parse(value);  
  23.             //5,使用TopDocs接收indexSearcher.searche的返回值  
  24.             TopDocs topDocs=indexSearcher.search(query,100);  
  25.             ScoreDoc[] scoreDocs=topDocs.scoreDocs;  
  26.             //6,获取Document输出  
  27.             System.err.println("total hit:"+topDocs.totalHits);  
  28.             System.out.println("total document:"+scoreDocs.length);  
  29.             System.err.println("==================================================");  
  30.             for(int i=0;i<scoreDocs.length;i++){  
  31.                 Document doc=indexSearcher.doc(scoreDocs[i].doc);  
  32.                 System.out.println("name:"+doc.get("name"));  
  33.                 System.err.println("title:"+doc.get("title"));  
  34.                 System.out.println("score:"+scoreDocs[i].score);  
  35.                 System.err.println("content:"+doc.get("content").substring(080));  
  36.             }  
  37.         } catch (CorruptIndexException e) {  
  38.             e.printStackTrace();  
  39.         } catch (IOException e) {  
  40.             e.printStackTrace();  
  41.         } catch (ParseException e) {  
  42.             e.printStackTrace();  
  43.         }  
  44.     }  
  45. }  
  • 测试检索
[java] view plain copy
  1. package org.xiaom.lucene;  
  2.   
  3. import java.io.IOException;  
  4.   
  5. public class LuceneTest {  
  6. public static void main(String[] args) throws IOException {  
  7.     String docPath="D:/test1/docs";  
  8.     String indexPath="D:/test1/index";  
  9.     MyIndexCreater.createContainChild(docPath, indexPath);  
  10.     MyIndexSearcher.search(indexPath, "content""adfddd");  
  11. }  
  12. }  

这里是一个Lucene3.5入门实例下载
  • 维护索引

维护索引一般有如下几种操作

  • 增加索引(见上文)
  • 删除索引
[java] view plain copy
  1. //删除某些满足条件的索引及Document  
  2.     public boolean delete(Term term){  
  3.         boolean rs=true;  
  4.         try {  
  5.             indexWriter.deleteDocuments(term);  
  6.         } catch (CorruptIndexException e) {  
  7.             e.printStackTrace();  
  8.             rs=false;  
  9.         } catch (IOException e) {  
  10.             rs=false;  
  11.             e.printStackTrace();  
  12.         }  
  13.         return rs;  
  14.     }  


  • 更新(删除索引后新增)索引
[java] view plain copy
  1. public boolean update(Document doc){  
  2.         boolean rs=true;  
  3.         try {  
  4.             indexWriter.addDocument(doc);  
  5.         } catch (CorruptIndexException e) {  
  6.             rs=false;  
  7.             e.printStackTrace();  
  8.         } catch (IOException e) {  
  9.             rs=false;  
  10.             e.printStackTrace();  
  11.         }  
  12.         return rs;  
  13.     }  

  • 合并索引文件
public void addIndexes(Directory... dirs)将dirs中索引合并到IndexWriter中,等待commit。
原创粉丝点击