现在的位置: 首页 > 综合 > 正文

lucene的索引建立及查找

2013年09月07日 ⁄ 综合 ⁄ 共 3411字 ⁄ 字号 评论关闭
Java代码 复制代码 收藏代码
  1. package lucene;   
  2.   
  3. import org.apache.lucene.analysis.standard.StandardAnalyzer;   
  4. import org.apache.lucene.document.Document;   
  5. import org.apache.lucene.document.Field;   
  6. import org.apache.lucene.index.IndexWriter;   
  7. import org.apache.lucene.queryParser.QueryParser;   
  8. import org.apache.lucene.search.Hits;   
  9. import org.apache.lucene.search.IndexSearcher;   
  10. import org.apache.lucene.search.Query;   
  11. import org.apache.lucene.store.FSDirectory;   
  12.   
  13. public class FSDirectoryTest {   
  14.   
  15.     //建立索引的路径      
  16.     public static final String path = "f://index2";   
  17.   
  18.     public static void main(String[] args) throws Exception {   
  19.         Document doc1 = new Document();   
  20.         doc1.add(new Field("name""lighter javaeye com", Field.Store.YES, Field.Index.TOKENIZED));   
  21.   
  22.         Document doc2 = new Document();   
  23.         doc2.add(new Field("name""lighter blog", Field.Store.YES, Field.Index.TOKENIZED));   
  24.   
  25.         IndexWriter writer = new IndexWriter(FSDirectory.getDirectory(path, true), new StandardAnalyzer(), true);   
  26.         writer.setMaxFieldLength(3);   
  27.         writer.addDocument(doc1);   
  28.         writer.setMaxFieldLength(3);   
  29.         writer.addDocument(doc2);   
  30.         writer.close();   
  31.   
  32.         IndexSearcher searcher = new IndexSearcher(path);   
  33.         Hits hits = null;   
  34.         Query query = null;   
  35.         QueryParser qp = new QueryParser("name"new StandardAnalyzer());   
  36.   
  37.         query = qp.parse("lighter");   
  38.         hits = searcher.search(query);   
  39.         System.out.println("查找/"lighter/" 共" + hits.length() + "个结果");   
  40.   
  41.         Document doc = null;   
  42.         for (int i = 0; i < hits.length(); i++) {   
  43.             doc = hits.doc(i);   
  44.             System.out.println(doc.get("name"));   
  45.             doc = null;   
  46.         }   
  47.   
  48.         query = qp.parse("javaeye");   
  49.         hits = searcher.search(query);   
  50.         System.out.println("查找/"javaeye/" 共" + hits.length() + "个结果");   
  51.   
  52.     }   
  53.   
  54. }  

 

附件为相关JAR包

【上篇】
【下篇】

抱歉!评论已关闭.