一、lucene简单的增删改查,如果是新项目,在做完对数据库的DAO操作时,紧跟着做对索引库的增删改查,在维护以前的项目时,再不允许修改源代码的情况下,只能做定时创建索引
package com.lucene.luceneutil;
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 com.lucene.entity.ArticleEntity;
public class ArticleDocumentUtils {
/**
* 把ArticleEntity转换成Document对象
* @param article ArticleEntity对象
* @return 转换后的doc对象
*/
public static Document Article2Document(ArticleEntity article){
String strId = article.getId().toString();
Document doc = new Document();
doc.add(new Field("id",strId,Store.YES,Index.NOT_ANALYZED));
doc.add(new Field("title",article.getTitle(),Store.YES,Index.ANALYZED));
doc.add(new Field("content",article.getContent(),Store.YES,Index.ANALYZED));
return doc ;
}
public static ArticleEntity Document2Article(Document doc){
ArticleEntity article = new ArticleEntity();
Integer id = Integer.parseInt(doc.get("id")) ;
article.setId(id);
article.setTitle(doc.get("title"));
article.setContent(doc.get("content"));
return article ;
}
}
package com.lucene.luceneutil;
import java.io.File;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
public class Configuration {
private static Directory directory ;
private static Analyzer analyzer ;
static {
try {
directory = FSDirectory.open(new File("./filepath"));
analyzer = new StandardAnalyzer(Version.LUCENE_30 );
} catch (Exception e) {
new RuntimeException(e);
}
}
public static Directory getDirectory() {
return directory;
}
public static Analyzer getAnalyzer() {
return analyzer;
}
}
package com.lucene.entity;
import java.util.List;
public class QueryResult<T> {
private int count ;
private List<T> list ;
public QueryResult(int count, List<T> list) {
this.count = count;
this.list = list;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public List<T> getList() {
return list;
}
public void setList(List<T> list) {
this.list = list;
}
}
package com.lucene.indexdao;
import com.lucene.entity.ArticleEntity;
import com.lucene.entity.QueryResult;
public interface ArticleEntityIndexDao {
/**
* 建立索引(保存到索引库)
*
* @param article
*/
public void save(ArticleEntity article);
/**
* 删除索引
* @param id
*/
public void delete(Integer id);
/**
* 更新文章
* @param article 要更新的文章
*/
public void update(ArticleEntity article) ;
/**
*
* @param query 查询条件
* @param firstResult 每页开始的条数
* @param number 每页显示的条数
* @return 返回符合条件的结果
*/
public QueryResult<ArticleEntity> search(String query,int firstResult ,int number);
}
package com.lucene.indexdao.impl;
import java.util.ArrayList;
import java.util.List;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriter.MaxFieldLength;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryParser.MultiFieldQueryParser;
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.util.Version;
import com.lucene.entity.ArticleEntity;
import com.lucene.entity.QueryResult;
import com.lucene.indexdao.ArticleEntityIndexDao;
import com.lucene.luceneutil.ArticleDocumentUtils;
import com.lucene.luceneutil.Configuration;
public class ArticleEntityIndexDaoImpl implements ArticleEntityIndexDao {
@Override
public void save(ArticleEntity article) {
// 1,把Article转为Document
Document doc = ArticleDocumentUtils.Article2Document(article);
// 2,把Document存到索引库中
IndexWriter indexWrite = null ;
try {
indexWrite = new IndexWriter(Configuration.getDirectory(), Configuration.getAnalyzer(), MaxFieldLength.LIMITED);
indexWrite.addDocument(doc);// 建立索引
} catch (Exception e) {
throw new RuntimeException(e);
}finally{
try {
indexWrite.close();
} catch (Exception e) {
throw new RuntimeException();
}
}
}
/**
* Term:就是某Field中的某个关键词。
*/
@Override
public void delete(Integer id) {
IndexWriter indexWrite = null ;
try {
Term term = new Term("id",id.toString());
indexWrite = new IndexWriter(Configuration.getDirectory(), Configuration.getAnalyzer(), MaxFieldLength.LIMITED);
indexWrite.deleteDocuments(term);
} catch (Exception e) {
throw new RuntimeException(e);
}finally{
try {
indexWrite.close();
} catch (Exception e) {
throw new RuntimeException();
}
}
}
/**
* 更新就是先删除再添加
*/
@Override
public void update(ArticleEntity article) {
IndexWriter indexWrite = null ;
try {
Term term = new Term("id",article.toString());
Document doc = ArticleDocumentUtils.Article2Document(article);
indexWrite = new IndexWriter(Configuration.getDirectory(), Configuration.getAnalyzer(), MaxFieldLength.LIMITED);
indexWrite.updateDocument(term, doc);
//indexWrite.deleteDocuments(term);
//indexWrite.addDocument(doc);
} catch (Exception e) {
throw new RuntimeException(e);
}finally{
try {
indexWrite.close();
} catch (Exception e) {
throw new RuntimeException();
}
}
}
@Override
public QueryResult<ArticleEntity> search(String query, int firstResult,int number) {
IndexSearcher searchQuery = null ;
QueryParser queryParser = null;
Query queryStr;
try {
//queryParser = new QueryParser(Version.LUCENE_30, "title", Configuration.getAnalyzer());这是默认在title里搜索
queryParser = new MultiFieldQueryParser(Version.LUCENE_30,new String[]{"title","content"}, Configuration.getAnalyzer());//多字段中搜索
queryStr = queryParser.parse(query);
searchQuery = new IndexSearcher(Configuration.getDirectory());
TopDocs topDocs = searchQuery.search(queryStr, 1000);
int totalNum = topDocs.totalHits ;//符合条件的总记录数
ScoreDoc[] scoredoc = topDocs.scoreDocs ;//符合条件的前n条信息
//处理结果
List<ArticleEntity> list = new ArrayList();
int endLenght = Math.max(firstResult+number, scoredoc.length);
for(int i = firstResult ; i < endLenght ; i++){
Document doc = searchQuery.doc(scoredoc[i].doc) ; //得到Document对象
ArticleEntity e =ArticleDocumentUtils.Document2Article(doc); //得到ArticleEntity对象
list.add(e);
}
return new QueryResult(totalNum,list);
} catch (Exception e) {
throw new RuntimeException(e);
}finally{
try {
searchQuery.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
}
二、对简单的增删改查做完了,单个的测试是没有问题,但是同时有多个IndexWriter在运行的时候就会出现org.apache.lucene.store.LockObtainFailedException: Lock obtain timed out: NativeFSLock@E:\indexDir\write.lock的一场,所以对于一个索引库,只能有一个打开IndexWtriter操作他,如果打开了多个,就会有上面的异常。