基于jeesite的cms系统(六):Lucene全文搜索引擎

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));

猜你喜欢

转载自www.cnblogs.com/Vito-Yan/p/10499422.html
今日推荐