lucene 3.0学习笔记(2)-使用索引查询(转)

上一篇中我们已经建好了索引,下面该使用索引来做正事了。 



这是一段实施基本搜索功能的代码示例: 

Java代码 
  1. Directory dir = FSDirectory.open(new File("index")));  
  2. IndexSearcher searcher = new IndexSearcher(dir, true);  
  3. Query q = new TermQuery(new Term("contents""java"));  
  4. TopDocs hits = searcher.search(q, 10);  
  5. searcher.close();  
使用索引进行查询的主要步骤: 

1、打开已有的索引,创建IndexSearcher对象 

2、指定查询用到的Field和查询字符串,创建TermQuery 

3、使用IndexSearcher进行查询,查询结果以TopDocs对象返回。在这里search方法的第二个参数指定返回前N个记录。 



主要对象说明: 

1、Term 

     Term是查询使用的基本单位,对应与在索引中使用的Field类。可以将其理解为一个map,其中key为索引中Field name,value为查询字符串。 

     当查询字符串为一个单词的情况下,不会有任何问题;但是当需要查询查询字符串为多个单词或是一句话的时候就会查不出来。这个主要原因是,在建立索引时我们对Field中的内容进行了分词,但在查询时,对查询字符串没有做分词,整个做为一个单词处理,当然查不到了。 

     要解决这个问题,针对上面的例子,只需要去掉new TermQuery这句,换成下面的代码: 
//处理输入的查询字符串 
Java代码 
  1. Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_CURRENT);  
  2. QueryParser parser = new QueryParser(Version.LUCENE_CURRENT, "java", analyzer);  
  3. Query query = parser.parse(queries);  


这里需要保证使用的analyzer与建立索引时用的一样即可。new QueryParser的第二个参数就是查询字符串。 

     我们用query.toString()可以看到转化后的Term内容。 

•当查询字符串="java"时,query.toString()=contents:java (前面为field name,后面为查询内容) 
•当查询字符串="java and system"时,query.toString()=contents:java contents:system。可见已经被做了分词,同时去掉了连接字and 
2、TopDocs 

     此类封装了返回的符合条件的记录,其中: 

•totalHits为符合条件的记录总数; 
•scoreDocs为符合条件记录的数组,不过里面只记录了Document的ID。Document的实际内容,需通过IndexSearcher取docID对应的Document才能得到。 
     需要注意-若设置在search方法中设置了返回记录数为N,则scoreDocs最多只会包含前N个文档;但是totalHits会返回匹配的总数量(类似google中显示的匹配的总页面数量)。scoreDocs.length可能不等于totalHits,做scoreDocs遍历时,直接用totalHits做为数组大小用的,容易引起bug! 



     另外取符合条件Document实际内容的代码如下: 

//显示查询结果,字段包括:路径、修改时间 
Java代码 
  1. private void printDocs(Searcher searcher, TopDocs docs)  
  2.     {  
  3.         try  
  4.         {  
  5.             System.out.println("Find " + docs.totalHits + " files!");  
  6.             ScoreDoc[] sd = docs.scoreDocs;  
  7.             for (int i = 0; i < sd.length; i++)  
  8.             {  
  9.                 Document doc = searcher.doc(sd[i].doc);  
  10.                 System.out.println("Path:" + doc.get("path") + "; modified:" + doc.get("modified"));  
  11.             }  
  12.         }  
  13.         catch(Exception ex)  
  14.         {  
  15.             System.out.println(ex.getMessage());  
  16.         }  
  17.     }  



DEMO: 

Java代码 
  1. public class Indexer {  
  2.   
  3.     /** 
  4.      * @param args 
  5.      * @throws IOException  
  6.      */  
  7.     public static void main(String[] args) throws IOException {  
  8.         //保存索引文件的地方  
  9.         String indexDir = "c:\\indexDir";  
  10.         //将要搜索TXT文件的地方  
  11.         String dateDir = "c:\\dateDir";  
  12.         IndexWriter indexWriter = null;  
  13.         //创建Directory对象  
  14.         Directory dir = new SimpleFSDirectory(new File(indexDir));  
  15.         //创建IndexWriter对象,第一个参数是Directory,第二个是分词器,第三个表示是否是创建,如果为false为在此基础上面修改,第四表示表示分词的最大值,比如说new MaxFieldLength(2),就表示两个字一分,一般用IndexWriter.MaxFieldLength.LIMITED   
  16.         indexWriter = new IndexWriter(dir,new StandardAnalyzer(Version.LUCENE_30),true,IndexWriter.MaxFieldLength.UNLIMITED);  
  17.         File[] files = new File(dateDir).listFiles();  
  18.         for (int i = 0; i < files.length; i++) {  
  19.             Document doc = new Document();  
  20.             //创建Field对象,并放入doc对象中  
  21.             doc.add(new Field("contents"new FileReader(files[i])));   
  22.             doc.add(new Field("filename", files[i].getName(),   
  23.                                 Field.Store.YES, Field.Index.NOT_ANALYZED));  
  24.             doc.add(new Field("indexDate",DateTools.dateToString(new Date(), DateTools.Resolution.DAY),Field.Store.YES,Field.Index.NOT_ANALYZED));  
  25.             //写入IndexWriter  
  26.             indexWriter.addDocument(doc);  
  27.         }  
  28.         //查看IndexWriter里面有多少个索引  
  29.         System.out.println("numDocs"+indexWriter.numDocs());  
  30.         indexWriter.optimize();  
  31.         indexWriter.close();  
  32.           
  33.     }  
  34.   
  35. }  


Java代码 
  1. public class Searcher {  
  2.   
  3.     public static void main(String[] args) throws IOException, ParseException {  
  4.         //保存索引文件的地方  
  5.         String indexDir = "c:\\indexDir";  
  6.         Directory dir = new SimpleFSDirectory(new File(indexDir));  
  7.         //创建 IndexSearcher对象,相比IndexWriter对象,这个参数就要提供一个索引的目录就行了  
  8.         IndexSearcher indexSearch = new IndexSearcher(dir);  
  9.         //创建QueryParser对象,第一个参数表示Lucene的版本,第二个表示搜索Field的字段,第三个表示搜索使用分词器  
  10.         QueryParser queryParser = new QueryParser(Version.LUCENE_30,  
  11.                 "contents"new StandardAnalyzer(Version.LUCENE_30));  
  12.         //生成Query对象  
  13.         Query query = queryParser.parse("liliugen");  
  14.         //搜索结果 TopDocs里面有scoreDocs[]数组,里面保存着索引值  
  15.         TopDocs hits = indexSearch.search(query, 10);  
  16.         //hits.totalHits表示一共搜到多少个  
  17.         System.out.println("找到了"+hits.totalHits+"个");  
  18.         //循环hits.scoreDocs数据,并使用indexSearch.doc方法把Document还原,再拿出对应的字段的值  
  19.         for (int i = 0; i < hits.scoreDocs.length; i++) {  
  20.             ScoreDoc sdoc = hits.scoreDocs[i];  
  21.             Document doc = indexSearch.doc(sdoc.doc);  
  22.             System.out.println(doc.get("filename"));              
  23.         }         
  24.         indexSearch.close();  
  25.     }  
  26. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值