日期:2014-05-19  浏览次数:20748 次

Lucence索引创建 [待改进]


import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

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.document.LongField;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.document.Field.Store;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.index.IndexWriterConfig.OpenMode;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

public class IndexerHelper {

  public enum CreateMode {
  CREATE, UPDATE
  }

  /**
  * 描述:生成索引文件
  * 
  * @param args 命令行指令
  * "-index/-i",以下为索引存储目录
  * "-source/-s",以下为索引源目录
  * "-update/-u",更新操作 <BR/>
  * @return Usage: java ConstructIndexer [-index/-i] "c:\index" [-source/s] "c:\source" [[-update/-u] / isNull]
  * @see java.lang.String.equalsIgnoreCase()
  * @throws IOException
  */
  public static void create(String[] args) {
  if (args == null || args.length >= 4) {
  System.out.println("Usage:java ConstructIndexer [-index/-i] \"c:\\index\" [-source/s] \"c:\\source\" [[-update/-u] / isNull]");
  System.exit(1);
  }
  String iDir = null, sDir = null;
  boolean update = false;
  for (int a = 0; a < args.length; a++) {
  if ("-index".equalsIgnoreCase(args[a])) {
  iDir = args[a + 1];
  }
  else if ("-source".equalsIgnoreCase(args[a])) {
  sDir = args[a + 1];
  }
  else if ("-update".equalsIgnoreCase(args[a])) {
  update = true;
  }
  }
  File idx = new File(iDir);
  if (!idx.exists() || !idx.isDirectory()) {
  System.out.println("Index directory is not exist.");
  System.exit(1);// by exception interrupt
  }
  Directory directory;
  try {
  directory = FSDirectory.open(idx);
  // open the index directory
  Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_40);
  IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_40, analyzer);
  config.setOpenMode(update ? OpenMode.CREATE_OR_APPEND : OpenMode.CREATE);
  IndexWriter writer = new IndexWriter(directory, config);
  addDocs(writer, sDir);
  writer.commit();
  writer.close();
  }
  catch (IOException e) {
  e.printStackTrace();
  }
  }

  public static void create(String iDir, String sDir, CreateMode mode