Lucene的小入门后续

1.高亮显示

 //演示Lucene的高亮显示
    @Test
    public void testHighLight() throws ParseException, IOException, InvalidTokenOffsetsException {
        QueryParser parser = new QueryParser(Version.LATEST, "content", new IKAnalyzer());
        Query query = parser.parse("谷歌");
        //设置高亮显示格式,两个参数(html的头标签和尾标签)
        SimpleHTMLFormatter formatter = new SimpleHTMLFormatter("<font color='red'>", "</font>");
        //创建高亮显示对象
        Highlighter highlighter = new Highlighter(formatter, new QueryScorer(query));
        //创建索引搜索器并指定索引库的位置
        IndexSearcher indexSearcher = new IndexSearcher(DirectoryReader.open(FSDirectory.open(new File("e:/tmp"))));
        TopDocs topDocs = indexSearcher.search(query, Integer.MAX_VALUE);
        System.out.println(topDocs.totalHits);
        ScoreDoc[] scoreDocs = topDocs.scoreDocs;
        for (ScoreDoc scoreDoc :
                scoreDocs) {
            Document doc = indexSearcher.doc(scoreDoc.doc);
            String bestFragment = highlighter.getBestFragment(new IKAnalyzer(), "content", doc.get("content"));
            System.out.println(bestFragment);
        }
    }

2.分页搜索

 //测试Lucene的分页
    @Test
    public void testLucenePageable() throws IOException {
        //设置页码
        int pageNum = 1;
        //设置总页数
        int totalPagenum = 3;
        //设置每页显示数量
        int pageSize = 3;
        //计算起始位置
        int startIndex = (totalPagenum-pageNum)*pageSize;
        //计算终点
        int endIndex = pageNum*pageSize;
        TermQuery query = new TermQuery(new Term("content", "谷歌"));
        IndexSearcher indexSearcher = new IndexSearcher(DirectoryReader.open(FSDirectory.open(new File("e:/tmp"))));
        TopDocs topDocs = indexSearcher.search(query, endIndex);
        System.out.println(topDocs);
        ScoreDoc[] scoreDocs = topDocs.scoreDocs;
        for (ScoreDoc scoreDoc :
                scoreDocs) {
            System.out.println(scoreDoc.doc);
            Document doc = indexSearcher.doc(scoreDoc.doc);
            System.out.println(doc.get("content"));
        }
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值