lucene

Posted 编世界

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了lucene相关的知识,希望对你有一定的参考价值。

public class Indexer {
    public void  index() throws IOException {
        //创建dicti
    //    Directory dir =  new RAMDirectory();
        Directory dir = FSDirectory.open(Paths.get("I:/testDemo/lucene/"));
        //indexWriter
        Analyzer analyzer = new StandardAnalyzer();
        IndexWriterConfig conf = new IndexWriterConfig(analyzer);
        IndexWriter writer=null;
        try {
            writer = new IndexWriter(dir, conf);
            File file = new File("I:/testDemo/data");
            for(File f : file.listFiles()){
                Document doc = new  Document();
                doc.add(new TextField("content", new FileReader(f)));
                doc.add(new TextField("name", f.getName(), Store.YES));
                doc.add(new TextField("path", f.getAbsolutePath(), Store.YES));
                writer.addDocument(doc);
            }
            
        } catch (Exception e) {
            
        }finally{
            try {
                if(writer!=null) writer.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        
    }
    
    public void searcher() throws IOException, ParseException{
        Directory dir = FSDirectory.open(Paths.get("I:/testDemo/lucene/"));
        IndexReader reader=DirectoryReader.open(dir);
        IndexSearcher isearcher = new IndexSearcher(reader);
        Analyzer analyzer=new StandardAnalyzer(); // 标准分词器
        QueryParser parser=new QueryParser("content", analyzer);
        Query query=parser.parse("REPRODUCTION");
        long start=System.currentTimeMillis();
        TopDocs hits=isearcher.search(query, 10);
        long end=System.currentTimeMillis();
        System.out.println("匹配 "+"REPRODUCTION"+" ,总共花费"+(end-start)+"毫秒"+"查询到"+hits.totalHits+"个记录");
        for(ScoreDoc scoreDoc:hits.scoreDocs){
            Document doc=isearcher.doc(scoreDoc.doc);
            System.out.println(doc.get("path"));
        }
        reader.close();
    }
    
    public static void main(String[] args) {
        Indexer indexer = new Indexer();
        try {
            indexer.index();
            indexer.searcher();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

 

以上是关于lucene的主要内容,如果未能解决你的问题,请参考以下文章

lucene demo代码

三搜索引擎篇-lucene入门代码示例

ElasticSearch 学习笔记一 简介

Lucene学习总结

Lucene分析

1. 初识 Lucene