码迷,mamicode.com
首页 > Web开发 > 详细

lucene中文分词搜索的核心代码

时间:2017-04-23 13:19:27      阅读:198      评论:0      收藏:0      [点我收藏+]

标签:search   ati   image   parse   out   public   bsp   分词器   att   

    public static void search(String indexDir,String q)throws Exception{
        Directory dir=FSDirectory.open(Paths.get(indexDir));
        IndexReader reader=DirectoryReader.open(dir);
        IndexSearcher is=new IndexSearcher(reader);
        // Analyzer analyzer=new StandardAnalyzer(); // 标准分词器
        SmartChineseAnalyzer analyzer=new SmartChineseAnalyzer();
        QueryParser parser=new QueryParser("desc", analyzer);
        Query query=parser.parse(q);
        long start=System.currentTimeMillis();
        TopDocs hits=is.search(query, 10);
        long end=System.currentTimeMillis();
        System.out.println("匹配 "+q+" ,总共花费"+(end-start)+"毫秒"+"查询到"+hits.totalHits+"个记录");
        
        QueryScorer scorer=new QueryScorer(query);
        Fragmenter fragmenter=new SimpleSpanFragmenter(scorer);
        SimpleHTMLFormatter simpleHTMLFormatter=new SimpleHTMLFormatter("<b><font color=‘red‘>","</font></b>");
        Highlighter highlighter=new Highlighter(simpleHTMLFormatter, scorer);
        highlighter.setTextFragmenter(fragmenter);
        for(ScoreDoc scoreDoc:hits.scoreDocs){
            Document doc=is.doc(scoreDoc.doc);
            System.out.println(doc.get("city"));
            System.out.println(doc.get("desc"));
            String desc=doc.get("desc");
            if(desc!=null){
                TokenStream tokenStream=analyzer.tokenStream("desc", new StringReader(desc));
                System.out.println(highlighter.getBestFragment(tokenStream, desc));
            }
        }
        reader.close();
    }

 

技术分享

 

lucene中文分词搜索的核心代码

标签:search   ati   image   parse   out   public   bsp   分词器   att   

原文地址:http://www.cnblogs.com/hzzhero/p/6752216.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!