欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

lucene 多字段查询+文字高亮显示

程序员文章站 2022-03-05 12:42:05
...
先创建索引,lucene3.0

Directory directory = null;
IndexSearcher isearcher = null;

Analyzer analyzer = new IKAnalyzer();

directory = new SimpleFSDirectory(new File("D:\data"));
isearcher = new IndexSearcher(directory); //创建索引

//在索引器中使用IKSimilarity相似度评估器 分词器
isearcher.setSimilarity(new IKSimilarity());

BooleanQuery bQuery = new BooleanQuery(); //组合查询

Query keywordQuery=null;

BooleanClause.Occur[] flags = {BooleanClause.Occur.SHOULD,BooleanClause.Occur.SHOULD,BooleanClause.Occur.SHOULD}; //OR 或者

keywordQuery = MultiFieldQueryParser.parse(Version.LUCENE_30,word,new String[]{"Title","Descripe","Keywords"},flags,analyzer); //多字段分词搜索

bQuery.add(keywordQuery, BooleanClause.Occur.MUST); //AND

if(username=="ddddd"){
Query courseQuery = new QueryParser(Version.LUCENE_30, "CourseName",analyzer).parse(course);
bQuery.add(courseQuery, BooleanClause.Occur.MUST);
}

//搜索相似度最高的5条记录
TopDocs topDocs = isearcher.search(bQuery , 500000);

//输出结果
ScoreDoc[] scoreDocs = topDocs.scoreDocs;
//关键字高亮显示
Formatter formatter = new SimpleHTMLFormatter("<font color=\"red\">", "</font>"); //前缀和后缀
Scorer scorer = new QueryScorer(bQuery);

Highlighter highlighter = new Highlighter(formatter, scorer);

highlighter.setTextFragmenter(new SimpleFragmenter(200)); //字长度
//高亮结束



[code]for(int i=0;i<10;i++){
Document targetDoc = isearcher.doc(scoreDocs[i].doc);
resourceIndex = new ResourceIndex();//存放的javabean
String title="";
title = highlighter.getBestFragment(analyzer, "Title", targetDoc.get("Title")); //高亮显示标题
if(title==null){
resourceIndex.setTitle(targetDoc.get("Title"));
} else {
resourceIndex.setTitle(title);
}
String Descripe = highlighter.getBestFragment(analyzer,
"Descripe", targetDoc.get("Descripe"));
if (Descripe == null) {
resourceIndex.setDescripe(targetDoc.get("Descripe"));
} else {
resourceIndex.setDescripe(Descripe);
}
resourceIndex.setVersion(targetDoc.get("Version")); //如果不高亮显示则不判断

}[/code]

所需的包
相关标签: lucene