/**
* 更新索引中的数据
*/
public static void updateIndex()
{
System.out.println("更新开始==============");
try
{
IndexWriter write = new IndexWriter(dir, new StandardAnalyzer(
Version.LUCENE_30), true,
IndexWriter.MaxFieldLength.UNLIMITED);
Document docNew = new Document();
docNew.add(new Field("id", "123456", Field.Store.YES,
Field.Index.NOT_ANALYZED));
docNew.add(new Field("userName", "王五", Field.Store.YES,
Field.Index.ANALYZED));
docNew.add(new Field("comefrom", "北京", Field.Store.YES,
Field.Index.ANALYZED));
Term term = new Term("id", "123456");
/**
* 调用updateDocument的方法,传给它一个新的doc来更新数据,
* Term term = new Term("id","1234567");
* 先去索引文件里查找id为1234567的Doc,如果有就更新它(如果有多条,最后更新后只有一条)。如果没有就新增.
*
* 数据库更新的时候,我们可以只针对某个列来更新,而lucene只能针对一行数据更新。
*/
write.updateDocument(term, docNew);
write.commit();
write.close();
System.out.println("===========成功把张三改成王五===========");
}
catch (Exception e)
{
LOGGER.info(e.getMessage());
}
System.out.println("更新结束==============\n");
}
/**
* 查询字符串
* @param str
*/
public static void search(String str)
{
System.out.println("查询开始==============");
try
{
QueryParser queryParser = new QueryParser(Version.LUCENE_30, "userName",
new StandardAnalyzer(Version.LUCENE_30));
Query query = queryParser.parse(str);
IndexSearcher search = new IndexSearcher(dir);
TopDocs hits = search.search(query, 20);
/*
* 带参数的多个关键字解析
* Query q=parser.parse("太阳 月亮");
* queryParser.setDefaultOperator(queryParser.AND_OPERATOR);//同时含有多个关键字,如果是QueryParser.OR_OPERATOR表示或者
*/
if (hits.scoreDocs.length == 0 || hits == null)
{
System.out.println(" 没有搜索到'" + str + "' 查询结束\n");
return;
}
for (int i = 0; i < hits.scoreDocs.length; i++)
{
ScoreDoc sdoc = hits.scoreDocs[i];
Document doc = search.doc(sdoc.doc);
System.out.println("own id = " + doc.get("id"));
System.out.println("userName = " + doc.get("userName"));
System.out.println("come from = " + doc.get("comefrom"));
}
}
catch (Exception e)
{
LOGGER.info(e.getMessage());
}
System.out.println("查询结束==============\n");
}
}
lucene3.0 CRUD实例(二)
最新推荐文章于 2024-09-10 09:07:08 发布