【Lucene】Lucene中的CRUD

数据库 waitig 366℃ 百度已收录 0评论

首先写好工具类

package cn.qblank.util;

import java.io.File;
import java.lang.reflect.Method;

import org.apache.commons.beanutils.BeanUtils;
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.Field.Index;
import org.apache.lucene.document.Field.Store;
import org.apache.lucene.index.IndexWriter.MaxFieldLength;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

/**
 * Lucene工具类
 * @author Administrator
 *
 */
public class LuceneUtil {
	private static Directory directory ;
	private static Analyzer analyzer ; 
	private static Version version; 
	private static MaxFieldLength maxFieldLength;
	
	static{
		try {
			directory = FSDirectory.open(new File("F:/LuceneDB"));
			version = Version.LUCENE_30;
			analyzer = new StandardAnalyzer(version);
			maxFieldLength = MaxFieldLength.LIMITED;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * javabean转document
	 * @param obj
	 * @return
	 * @throws Exception
	 */
	public static Document javabean2documemt(Object obj) throws Exception{
		//创建document对象
		Document document = new Document();
		//获取字节码对象
		Class clazz = obj.getClass();
		//获取该对象中的私有属性: 使用强反射  这里使用类全称,防止和Lucene包起冲突
		java.lang.reflect.Field[] reflectfields = clazz.getDeclaredFields();
		
		//遍历字段
		for (java.lang.reflect.Field field : reflectfields) {
			//设置访问权限:因为字段是私有的
			field.setAccessible(true);
			String fieldName = field.getName();
			//给其拼装成get方法
			String methodName = "get" + fieldName.substring(0,1).toUpperCase() + fieldName.substring(1);
			
			Method method = clazz.getMethod(methodName, null);
			//调用方法
			String returnValue = method.invoke(obj, null).toString();
			
			document.add(new Field(fieldName, returnValue, Store.YES, Index.ANALYZED));
		}
		return document;
	}
	
	/**
	 * document转javabean,可以使用BeanUtils组件
	 * @throws Exception
	 */
	public static Object document2javabean(Document document,Class clazz) throws Exception{
		//先获取字节码对象
		Object obj = clazz.newInstance();
		//获取到各个字段名
		java.lang.reflect.Field[] reflectField = clazz.getDeclaredFields();
		for (java.lang.reflect.Field field : reflectField) {
			//设置访问权限
			field.setAccessible(true);
			//获取各个的字段名和值
			String fieldName = field.getName();
			String fieldValue = document.get(fieldName);
			//使用BeanUtils组件封装对象
			BeanUtils.setProperty(obj, fieldName, fieldValue);
		}
		return obj;
	}
	
	
	public static Directory getDirectory() {
		return directory;
	}
	public static Analyzer getAnalyzer() {
		return analyzer;
	}
	public static Version getVersion() {
		return version;
	}
	public static MaxFieldLength getMaxFieldLength() {
		return maxFieldLength;
	}

	
	

	
}


创建Student对象

package cn.qblank.lucene;

public class Student {
	private Integer id;
	private String name;
	private String describe;
	
	public Student(){}
	public Student(Integer id, String name, String describe) {
		super();
		this.id = id;
		this.name = name;
		this.describe = describe;
	}
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getDescribe() {
		return describe;
	}
	public void setDescribe(String destcribe) {
		this.describe = destcribe;
	}
	
	@Override
	public String toString() {
		return "编号:" + id + "\n" + "姓名:" + name +"\n" + "简历:" + describe;
	}
}

然后进行添加add

public void add() throws Exception {
	//创建IndexWriter对象
	IndexWriter indexWriter = new IndexWriter(LuceneUtil.getDirectory(), LuceneUtil.getAnalyzer(), LuceneUtil.getMaxFieldLength());
	//创建对象
	Student stu1 = new Student(1, "张三", "张三是一个好人");
	//将javabean转为document对象
	Document document1 = LuceneUtil.javabean2documemt(stu1);
	indexWriter.addDocument(document1);
	
	Student stu2 = new Student(2, "李四", "李四是一个好人");
	Document document2 = LuceneUtil.javabean2documemt(stu2);
	indexWriter.addDocument(document2);
	
	Student stu3 = new Student(3, "王五", "王五是一个好人");
	Document document3 = LuceneUtil.javabean2documemt(stu3);
	indexWriter.addDocument(document3);
	
	Student stu4 = new Student(4, "赵六", "赵六是一个好人");
	Document document4 = LuceneUtil.javabean2documemt(stu4);
	indexWriter.addDocument(document4);
	
	Student stu5 = new Student(5, "王麻子", "王麻子是一个好人");
	Document document5 = LuceneUtil.javabean2documemt(stu5);
	indexWriter.addDocument(document5);
	//关闭流
	indexWriter.close();
}

通过查询全部可以看到记录

public void findAllByKeywords() throws Exception {
	//存放封转结果对象的集合
	List<Student> arrayList = new ArrayList<Student>();
	//准备输入的值
	String keywords = "好";
	//创建IndexSearcher字符流对象
	IndexSearcher indexSearcher = new IndexSearcher(LuceneUtil.getDirectory());
	//创建QueryParser对象
	QueryParser queryParser = new QueryParser(LuceneUtil.getVersion(), "describe", LuceneUtil.getAnalyzer());
	//封转输入的数据
	Query query = queryParser.parse(keywords);
	//使用indexSearcher查询前100条记录
	TopDocs topDocs = indexSearcher.search(query, 100);
	//迭代出词汇表中符合条件的编号
	for (int i = 0; i < topDocs.scoreDocs.length; i++) {
		//取出封装编号和分数的ScoreDoc对象
		ScoreDoc scoreDoc = topDocs.scoreDocs[i];
		//获取结果编号
		int id = scoreDoc.doc;
		//根据编号去原始记录表中查询对应的document对象
		Document document = indexSearcher.doc(id);
		//将docuement对象封转成javabean
		Student student = (Student) LuceneUtil.document2javabean(document, Student.class);
		//将对象添加到集合中
		arrayList.add(student);
	}
			
	//遍历结果集合
	for (Student student : arrayList) {
		System.out.println(student);
	}
	//关闭indexSearcher流对象
	indexSearcher.close();
}

运行结果:



删除一条id为5的记录delete

public void delete() throws Exception {
	IndexWriter indexWriter = new IndexWriter(LuceneUtil.getDirectory(), LuceneUtil.getAnalyzer(), LuceneUtil.getMaxFieldLength());
	indexWriter.deleteDocuments(new Term("id","5"));
	indexWriter.close();
}


修改id为1的update,在这儿相当于添加了删了再添加

public void delete() throws Exception {
	IndexWriter indexWriter = new IndexWriter(LuceneUtil.getDirectory(), LuceneUtil.getAnalyzer(), LuceneUtil.getMaxFieldLength());
	indexWriter.deleteDocuments(new Term("id","5"));
	indexWriter.close();
}

删除所有deleteAll

public void deleteAll() throws Exception {
	IndexWriter indexWriter = new IndexWriter(LuceneUtil.getDirectory(), LuceneUtil.getAnalyzer(), LuceneUtil.getMaxFieldLength());
	indexWriter.deleteAll();
	indexWriter.close();
}








本文由【waitig】发表在等英博客
本文固定链接:【Lucene】Lucene中的CRUD
欢迎关注本站官方公众号,每日都有干货分享!
等英博客官方公众号
点赞 (0)分享 (0)