lucene3.0 CRUD实例(一)

鉴于网上Lucene3.0的操作介绍不够全面具体、特整理如下供大家参考
各位有好建议可共享!


创建、更新、查询索引 CRUDIndex.java

package com.wj.lucene;

import java.io.File;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
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;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.SimpleFSDirectory;
import org.apache.lucene.util.Version;

/**
 * Lucene3.0 CRUD操作
 * 更能如下:
 * 添加、追加、更新、查询所有、根据特定字符串查询
 * 
 * @author jcom
 * @date 2010-9-28
 *
 */
public class CRUDIndex
{
	private static final Log LOGGER = LogFactory.getLog(CRUDIndex.class);
			
	private static String path = "c:/index";
	
	private static Directory dir = null;
	
	public static void main(String[] args) throws Exception
	{
		dir = new SimpleFSDirectory(new File(path)); 
		
		//添加查询
		addIndex();
		search("张三");
		
		//更新后再查询
		updateIndex();
		search("张三");
		search("王五");
	}

	/**
	 * 向索引中添加一条数据
	 */
	public static void addIndex()
	{
		System.out.println("添加开始--------------");
		try
		{
			/**
			 * 创建IndexWriter对象, 
			 * 第一个参数是Directory, 
			 * 第二个是分词器,
			 * 第三个表示是否是创建, 如果为false为在此基础上面修改, 
			 * 第四表示表示分词的最大值,比如说new MaxFieldLength(2),就表示两个字一分,一般用IndexWriter.MaxFieldLength.LIMITED
			 */
			IndexWriter write = new IndexWriter(dir, new StandardAnalyzer(
					Version.LUCENE_30), true,
					IndexWriter.MaxFieldLength.UNLIMITED);
			
			Document doc = new Document();
			doc.add(new Field("id", "123456", Field.Store.YES,
					Field.Index.NOT_ANALYZED));
			doc.add(new Field("userName", "张三", Field.Store.YES,
					Field.Index.ANALYZED));
			doc.add(new Field("comefrom", "北京", Field.Store.YES,
					Field.Index.ANALYZED));
			
			write.addDocument(doc);
			
			write.commit();
			write.close();
		} 
		catch (Exception e)
		{
			LOGGER.info(e.getMessage());
		}
		System.out.println("添加结束--------------\n");
	}

你可能感兴趣的:(apache,Lucene)