lucene源码分析---1

lucene源码分析—实例

本章开始分析lucene的源码,版本为目前最新的6.1.0,下面先看一段常见的lucene建立索引和进行搜索的实例,

建立索引实例:

            String filePath = ...//文件路径
            String indexPath = ...//索引路径
            File fileDir = new File(filePath);    
            Directory dir = FSDirectory.open(Paths.get(indexPath));  

            Analyzer luceneAnalyzer = new StandardAnalyzer();
            IndexWriterConfig iwc = new IndexWriterConfig(luceneAnalyzer);  
            iwc.setOpenMode(OpenMode.CREATE);  
            IndexWriter indexWriter = new IndexWriter(dir,iwc);    
            File[] textFiles = fileDir.listFiles();    

            for (int i = 0; i < textFiles.length; i++) {    
                if (textFiles[i].isFile()) {     
                    String temp = FileReaderAll(textFiles[i].getCanonicalPath(),    
                            "GBK");    
                    Document document = new Document();    
                    Field FieldPath = new StringField("path", textFiles[i].getPath(), Field.Store.YES);
                    Field FieldBody = new TextField("body", temp, Field.Store.YES);    
                    document.add(FieldPath);    
                    document.add(FieldBody);    
                    indexWriter.addDocument(document);    
                }    
            }    
            indexWriter.close();

其中,FileReaderAll函数用来从文件中读取字符串。

搜索实例:

            String indexPath=...//索引路径  
            IndexReader reader = DirectoryReader.open(FSDirectory.open(Paths.get(indexPath)));
            IndexSearcher searcher=new IndexSearcher(reader);
            ScoreDoc[] hits=null;  
            String queryString=...//关键字符串
            Query query=null;  
            Analyzer analyzer= new StandardAnalyzer();  
            try {  
                QueryParser qp=new QueryParser("body",analyzer);
                query=qp.parse(queryString);  
            } catch (ParseException e) {  

            }  
            if (searcher!=null) {  
                TopDocs results=searcher.search(query, 10);
                hits=results.scoreDocs;  
                Document document=null;  
                for (int i = 0; i < hits.length; i++) {  
                    document=searcher.doc(hits[i].doc);  
                    String body=document.get("body");  
                    String path=document.get("path");  
                    String modifiedtime=document.get("modifiField");  
                }  
                reader.close();  
            }  

后面的章节就会开始分析这两个实例究竟做了哪些工作,以及探究lucene背后的原理。

  • 0
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值