首页 技术 正文
技术 2022年11月12日
0 收藏 459 点赞 5,095 浏览 3526 个字

1、lucene初始化

//    @Value("${lucene.index.path}")
private String indexPath = "/Users/vitoyan/Downloads/Projects/jeesite-demo/lucene_index"; private Directory directory; private DirectoryReader reader; @PostConstruct
public void init() {
try {
directory = FSDirectory.open(Paths.get(indexPath));
} catch (IOException e) {
e.printStackTrace();
}
}

2、添加索引

/**
* 添加索引
*
* @param article
* @throws Exception
*/
public void add(JsCmsArticlesEntity article) throws GlobalException {
IndexWriter writer = null;
try {
Analyzer analyzer = new ComplexAnalyzer();
IndexWriterConfig iwc = new IndexWriterConfig(analyzer);
writer = new IndexWriter(directory, iwc);
Document doc = new Document();
doc.add(new TextField("id", String.valueOf(article.getId()), Field.Store.YES));
doc.add(new TextField("title", article.getTitle(), Field.Store.YES));
doc.add(new TextField("authorId", String.valueOf(article.getAuthorId()), Field.Store.YES));
doc.add(new TextField("content", article.getContent(), Field.Store.YES));
doc.add(new TextField("tags", article.getTags(), Field.Store.YES));
doc.add(new TextField("createAt", DateUtil.formateToStr(article.getCreateAt(), "yyyy-MM-dd"), Field.Store.YES));
writer.addDocument(doc);
} catch (Exception e) {
throw new GlobalException(500, e.toString());
} finally {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

3、查询数据

/**
* 查询数据
*
* @param keyword
* @return
*/
public List<JsCmsArticlesEntity> query(String keyword) throws GlobalException {
System.out.println(keyword);
try {
IndexSearcher searcher = this.getIndexSearcher();
Analyzer analyzer = new ComplexAnalyzer(); String[] fields = {"title"};// 使用多域查询,便于以后扩展
MultiFieldQueryParser multiFieldQueryParser = new MultiFieldQueryParser(fields, analyzer);
Query query = multiFieldQueryParser.parse(keyword); TopDocs topDocs = searcher.search(query, 100); // 1.格式化对象,设置前缀和后缀
Formatter formatter = new SimpleHTMLFormatter("<font color='red'>","</font>");
// 2.关键词对象
Scorer scorer = new QueryScorer(query);
// 3. 高亮对象
Highlighter highlighter = new Highlighter(formatter, scorer); List<JsCmsArticlesEntity> list = new ArrayList<>();
JsCmsArticlesEntity article;
ScoreDoc[] scoreDocs = topDocs.scoreDocs; for (ScoreDoc scoreDoc : scoreDocs) {
Document document = searcher.doc(scoreDoc.doc);
// if (Integer.parseInt(document.get("authorId")) == 1) {
article = new JsCmsArticlesEntity();
String titleHighLight = highlighter.getBestFragment(analyzer,"title",document.get("title"));
article.setId(Integer.parseInt(document.get("id")));
article.setTitle(titleHighLight);
article.setContent(document.get("content"));
article.setTags(document.get("tags"));
// article.setCreateAt((Timestamp) DateUtil.parseToDate(document.get("createAt"), "yyyy-MM-dd"));
list.add(article);
// }
}
return list;
} catch (Exception e) {
throw new GlobalException(500, e.toString());
}
} @Test
public void test() {
LuceneService luceneService = new LuceneService();
luceneService.init();
luceneService.query("123"); } private IndexSearcher getIndexSearcher() throws IOException {
if (reader == null) {
reader = DirectoryReader.open(directory);
} else {
DirectoryReader changeReader = DirectoryReader.openIfChanged(reader);
if (changeReader != null) {
reader.close();
reader = changeReader;
}
}
return new IndexSearcher(reader);
}

4、使用lucene(相关工具类和全局异常代码可以查看码云

在发布文章时添加文章索引到文件系统

luceneService.init();
luceneService.add(article);

或者一次添加所有索引

List<JsCmsArticlesEntity> articles = this.frontService.getAllArticles();
LuceneService luceneService = new LuceneService();
for (JsCmsArticlesEntity article : articles) {
luceneService.init();
luceneService.add(article);
System.out.println(article.getTitle());
}

然后查询数据

LuceneService luceneService = new LuceneService();
luceneService.init();
resp.setRespCode(JsCmsResponse.RESPCODE_SUCCESS);
resp.setMsgInfo("获取内容成功");
resp.setRespObj(luceneService.query(keyword));

    					
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,500
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,914
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,747
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,504
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,142
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,306