简单 Lucene 索引机制

        

简介Apache Lucene是一个基于Java全文搜索引擎,利用它可以轻易地为Java软件加入

 

全文搜寻功能。Lucene的最主要工作是替文件的每一个字作索引,索引让搜寻的效

 

率比传统的逐字比较大大提高,Lucen提供一组解读,过滤,分析文件,编排和使用

 

索引的API,它的强大之处除了高效和简单外,是最重要的是使使用者可以随时应自已

 

需要自订其功能。

 

     1. 准备文本文件        

                首先把一些以 txt 为后缀名的文本文件放到一个目录中,比如在

        Windows 平台上,你可以放到任意位置,

        比如:C:\\Users\\By More -02\\Workspaces\\MyEclipse 8.5\\lucene\\dataDir

  

     2.  先建一个项目,需去apache官方下载lucene类库包 ,下载地址,目前最新版本3.0.3

         本实例基于lucene 2.4 http://mirror.its.uidaho.edu/pub/apache//lucene/java/

  

     3. 创建索引 FileIndex.java 

 代码如下: 代码如下:package com.test.lucene;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.Date;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexWriter;

public class FileIndex {

 @SuppressWarnings("deprecation")
 public static void main(String[] args) throws Exception {

  // dataDir是文件目录,包含被索引的文本文件
  File dataDir = new File(Constants.INDEX_FILE_PATH);

  // indexDir创建索引存放的文件目录
  File indexDir = new File(Constants.INDEX_STORE_PATH);

  Analyzer luceneAnalyzer = new StandardAnalyzer();        //lucene3.0不支持此写法,需一个参数
  IndexWriter indexWriter = new IndexWriter(indexDir, luceneAnalyzer,
    true);
  File[] textFiles = dataDir.listFiles();
  // 获得开始时间
  long startTime = new Date().getTime();
  System.out.println("共搜索到:" + textFiles.length + "个文件");
  for (int i = 0; i < textFiles.length; i++) {
   if (textFiles[i].isFile()
     && textFiles[i].getName().endsWith(".txt")) {
    System.out.println("找到:" + textFiles[i].getCanonicalPath());

    BufferedReader reader = new BufferedReader(
      new InputStreamReader(new FileInputStream(textFiles[i])));

    StringBuffer content = new StringBuffer();

    for (String line = null; (line = reader.readLine()) != null;) {
     content.append(line).append("\n");
    }

    Document doc = new Document();
    doc.add(new Field("content", content.toString(),
      Field.Store.YES, Field.Index.ANALYZED));

    doc.add(new Field("fileName", textFiles[i].getName(),
      Field.Store.YES, Field.Index.ANALYZED));

    indexWriter.addDocument(doc);
   }

  }

  indexWriter.optimize();
  indexWriter.close();

  Long endTime = new Date().getTime();

  System.out.println("总用时间:" + (endTime - startTime) + "秒");
 }
}

       4.创建一个工具类 Constants.java       

代码如下:package com.test.lucene;

public class Constants {

 // 要建立索引的文件存放路径
 public static final String INDEX_FILE_PATH =
  "C:\\Users\\By More -02\\Workspaces\\MyEclipse 8.5\\lucene\\dataDir";

 // 索引存放的位置
 public static final String INDEX_STORE_PATH =
  "C:\\Users\\By More -02\\Workspaces\\MyEclipse 8.5\\lucene\\luceneIndex";
}

 

 

        5.创建搜索 FileSearcher.java

 

代码如下:package com.test.lucene;

import java.io.File;

import org.apache.lucene.document.Document;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.Hits;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

@SuppressWarnings("deprecation")
public class FileSearcher {

 public static void main(String[] args) throws Exception {

  // String queryStr = "网*";
  String queryStr = "桌";

  File indexDir = new File(Constants.INDEX_STORE_PATH);
  Directory directory = FSDirectory.getDirectory(indexDir);
  IndexSearcher searcher = new IndexSearcher(directory);
  if (!indexDir.exists()) {
   System.out.println("目录中不存在索引!");
   return;
  }
  Term term = new Term("content", queryStr.toLowerCase());
  // Query lucenequery =new WildcardQuery(term);

  TermQuery lucenequery = new TermQuery(term);
  Hits hits = searcher.search(lucenequery);
  System.out.println("共有" + hits.length() + "结果");
  for (int i = 0; i < hits.length(); i++) {
   Document doc = hits.doc(i);
   System.out.println("fileName:" + doc.get("fileName"));
   System.out.println("content:" + doc.get("content"));
  }
 }
}


         

 

      本实例项目源码下载地址: http://download.csdn.net/source/3072603 

 

posted @ 2011-03-08 13:51  kanjc  阅读(521)  评论(0编辑  收藏  举报