初试 Lucene 2

其他代码与添加一致,在添加 doc 时改为如下代码即可
indexWriter.updateDocument(new Term("id",index.getId()), document);
4、搜索 按照单个单词搜索
List<IndexModel> indexModels = new ArrayList<IndexModel>();
Directory directory = null;
try{
directory = FSDirectory.open(indexDir);
IndexSearcher indexSearcher = new IndexSearcher(directory);
//下面的是进行title,content 两个范围内进行收索.
BooleanClause.Occur[] clauses = { BooleanClause.Occur.SHOULD,BooleanClause.Occur.SHOULD ,BooleanClause.Occur.SHOULD};
Query queryOBJ = MultiFieldQueryParser.parse(Version.LUCENE_34, primarkStr, new String[]{"name","password","id"}, clauses, new StandardAnalyzer(Version.LUCENE_34));//parser.parse(query);
Filter filter = null;

//################# 搜索相似度最高的记录 ###################
TopDocs topDocs = indexSearcher.search(queryOBJ, filter, 1000);
//TopDocs topDocs = indexSearcher.search(queryOBJ , 10000);
System.out.println("*** 共匹配:" + topDocs.totalHits + "个 ***");
IndexModel indexModel = null;
//输出结果
for (ScoreDoc scoreDoc : topDocs.scoreDocs){
Document targetDoc = indexSearcher.doc(scoreDoc.doc);
indexModel = new IndexModel();
//设置高亮显示格式
SimpleHTMLFormatter simpleHTMLFormatter = new SimpleHTMLFormatter("<font color='red'><strong>", "</strong></font>");
/* 语法高亮显示设置 */
Highlighter highlighter = new Highlighter(simpleHTMLFormatter,new QueryScorer(queryOBJ));
highlighter.setTextFragmenter(new SimpleFragmenter(100));
String name;
name = targetDoc.get("name");
String createTime;
createTime = targetDoc.get("createTime");
String id;
id = targetDoc.get("id");
if(createTime == null){
createTime = "";
}
if(name == null){
name = "";
}
if(id == null){
id = "";
}
TokenStream titleTokenStream = analyzer.tokenStream("name",new StringReader(name));
TokenStream contentTokenStream = analyzer.tokenStream("createTime",new StringReader(createTime));
TokenStream idTokenStream = analyzer.tokenStream("id", new StringReader(id));
String highLightTitle = highlighter.getBestFragment(titleTokenStream, name);
String highLightContent = highlighter.getBestFragment(contentTokenStream, createTime);
String highLightid = highlighter.getBestFragment(idTokenStream, id);
if(highLightTitle == null)
highLightTitle = name;

if(highLightContent == null)
highLightContent = createTime;

if(highLightid == null)
highLightid = id;
indexModels.add(indexModel);
}
indexSearcher.close();
return indexModels;

}catch(Exception e){
e.printStackTrace();
return null;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值