一、lucene初始化git
// @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(); } }
二、添加索引工具
/** * 添加索引 * * @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(); } } }
三、查詢數據this
/** * 查詢數據 * * @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); }
四、使用lucene(相關工具類和全局異常代碼能夠查看碼雲)spa
在發佈文章時添加文章索引到文件系統code
luceneService.init();
luceneService.add(article);
或者一次添加全部索引orm
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));