lucene的搜索,TermQuery,TermRangeQuery,NumericRangeQuery

  1. SearchUtil.java 
  2. import java.io.File; 
  3. import java.io.IOException; 
  4. import java.text.ParseException; 
  5. import java.text.SimpleDateFormat; 
  6. import java.util.Date; 
  7.  
  8. import org.apache.lucene.analysis.standard.StandardAnalyzer; 
  9. import org.apache.lucene.document.Document; 
  10. import org.apache.lucene.document.Field; 
  11. import org.apache.lucene.document.NumericField; 
  12. import org.apache.lucene.index.CorruptIndexException; 
  13. import org.apache.lucene.index.IndexReader; 
  14. import org.apache.lucene.index.IndexWriter; 
  15. import org.apache.lucene.index.IndexWriterConfig; 
  16. import org.apache.lucene.index.Term; 
  17. import org.apache.lucene.search.IndexSearcher; 
  18. import org.apache.lucene.search.NumericRangeQuery; 
  19. import org.apache.lucene.search.Query; 
  20. import org.apache.lucene.search.ScoreDoc; 
  21. import org.apache.lucene.search.TermQuery; 
  22. import org.apache.lucene.search.TermRangeQuery; 
  23. import org.apache.lucene.search.TopDocs; 
  24. import org.apache.lucene.store.Directory; 
  25. import org.apache.lucene.store.FSDirectory; 
  26. import org.apache.lucene.store.LockObtainFailedException; 
  27. import org.apache.lucene.util.Version; 
  28.  
  29.  
  30. public class SearchUtil { 
  31.     private String[] ids = {"1","2","3","4","5","6"}; 
  32.     private String[] emails = {"[email protected]","[email protected]","[email protected]","[email protected]","[email protected]","[email protected]"}; 
  33.     private String[] content ={ 
  34.             "Welcome to Kenan my home"
  35.             "Hello Kenan "
  36.             "Good morning"
  37.             "Are you OK?"
  38.             "Yeah hahahahahahaha Kenan"
  39.             "I like foot ball" 
  40.     }; 
  41.     private int[] attachs = {1,4,6,2,3,8}; 
  42.     private Date[] dates = null
  43.     private String[] names = {"5555","333","44","111","222","666"}; 
  44.     //詞典  
  45.     private Directory directory = null
  46.     //寫入筆 
  47.     private IndexWriter writer = null
  48.     //文檔對象 
  49.     private Document doc = null
  50.     //讀取對象 
  51.     private IndexReader reader = null
  52.     private IndexSearcher searcher = null
  53.     private void datesInit() { 
  54.         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); 
  55.         dates = new Date[6]; 
  56.         try { 
  57.             dates[0] = sdf.parse("2010-12-01"); 
  58.             dates[1] = sdf.parse("2011-12-01"); 
  59.             dates[2] = sdf.parse("2001-12-01"); 
  60.             dates[3] = sdf.parse("2013-12-01"); 
  61.             dates[4] = sdf.parse("2003-12-01"); 
  62.             dates[5] = sdf.parse("2014-12-01"); 
  63.         } catch (ParseException e) { 
  64.             // TODO Auto-generated catch block 
  65.             e.printStackTrace(); 
  66.         } 
  67.     } 
  68.     public SearchUtil(){ 
  69.         datesInit(); 
  70.         try { 
  71.             directory = FSDirectory.open(new File("d:/lucene/index01")); 
  72.             buildIndex(); 
  73.             this.getSearcher(); 
  74.         } catch (IOException e) { 
  75.             // TODO Auto-generated catch block 
  76.             e.printStackTrace(); 
  77.         } 
  78.     } 
  79.     /** 
  80.      * 構建索引 
  81.      */ 
  82.     public void buildIndex(){ 
  83.         try { 
  84.             writer = new IndexWriter(directory,new IndexWriterConfig(Version.LUCENE_35, new StandardAnalyzer(Version.LUCENE_35))); 
  85.             for(int i=0;i<6;i++){ 
  86.                 doc = new Document(); 
  87.                 doc.add(new Field ("id",ids[i],Field.Store.YES,Field.Index.NOT_ANALYZED_NO_NORMS)); 
  88.                 doc.add(new Field("email",emails[i],Field.Store.YES,Field.Index.NOT_ANALYZED)); 
  89.                 doc.add(new Field("content",this.content[i],Field.Store.NO,Field.Index.ANALYZED)); 
  90.                 doc.add(new Field("name",this.names[i],Field.Store.YES,Field.Index.NOT_ANALYZED_NO_NORMS)); 
  91.                 //給數字加索引 
  92.                 doc.add(new NumericField("attach", Field.Store.YES,true).setIntValue(attachs[i])); 
  93.                 //給日期加索引 
  94.                 doc.add(new NumericField("date",Field.Store.YES,true).setLongValue(dates[i].getTime())); 
  95.                 writer.addDocument(doc); 
  96.             } 
  97.         } catch (CorruptIndexException e) { 
  98.             // TODO Auto-generated catch block 
  99.             e.printStackTrace(); 
  100.         } catch (LockObtainFailedException e) { 
  101.             // TODO Auto-generated catch block 
  102.             e.printStackTrace(); 
  103.         } catch (IOException e) { 
  104.             // TODO Auto-generated catch block 
  105.             e.printStackTrace(); 
  106.         }finally
  107.             if(writer != null){ 
  108.                 try { 
  109.                     writer.close(); 
  110.                 } catch (CorruptIndexException e) { 
  111.                     // TODO Auto-generated catch block 
  112.                     e.printStackTrace(); 
  113.                 } catch (IOException e) { 
  114.                     // TODO Auto-generated catch block 
  115.                     e.printStackTrace(); 
  116.                 } 
  117.             } 
  118.         } 
  119.     } 
  120.     public IndexSearcher getSearcher(){ 
  121.         try { 
  122.             if(reader == null){ 
  123.                 reader = IndexReader.open(directory); 
  124.             }else
  125.                 IndexReader ir = IndexReader.openIfChanged(reader); 
  126.                 if(ir!=null){ 
  127.                     reader.close(); 
  128.                     reader = ir; 
  129.                 } 
  130.             } 
  131.             searcher = new IndexSearcher(reader); 
  132.             return searcher; 
  133.         } catch (CorruptIndexException e) { 
  134.             // TODO Auto-generated catch block 
  135.             e.printStackTrace(); 
  136.         } catch (IOException e) { 
  137.             // TODO Auto-generated catch block 
  138.             e.printStackTrace(); 
  139.         } 
  140.         return null
  141.     } 
  142.     public void termQuery(String field,String name,int num){ 
  143.         Query query = new TermQuery(new Term(field, name)); 
  144.         try { 
  145.             TopDocs tds = this.searcher.search(query, num); 
  146.             System.out.println("查詢到的結果數:"+tds.totalHits); 
  147.             for(ScoreDoc sd : tds.scoreDocs){ 
  148.                 doc = this.searcher.doc(sd.doc); 
  149.                 System.out.println("id:"+doc.get("id")+"---"+"name:"+doc.get("name")+"---"+"attachs:"+doc.get("attach")+"---"+"email:"+doc.get("email")); 
  150.             } 
  151.         } catch (IOException e) { 
  152.             // TODO Auto-generated catch block 
  153.             e.printStackTrace(); 
  154.         } finally { 
  155.             try { 
  156.                 this.searcher.close(); 
  157.             } catch (IOException e) { 
  158.                 // TODO Auto-generated catch block 
  159.                 e.printStackTrace(); 
  160.             } 
  161.         } 
  162.     } 
  163.     /** 
  164.      *  
  165.      * @param field 要查詢的域 
  166.      * @param lowerTerm  開始的字符 
  167.      * @param upperTerm 結束的字符 
  168.      * @param num 查詢的top個數 
  169.      * @param includeLower 是否包含開始的邊界 
  170.      * @param includeUpper 是否包含結束的邊界 
  171.      */ 
  172.     public void termRangeQuery(String field,String lowerTerm,String upperTerm,int num,boolean includeLower, boolean includeUpper){ 
  173.          
  174.         Query query = new TermRangeQuery(field, lowerTerm, upperTerm, includeLower,includeUpper); 
  175.         try { 
  176.             TopDocs tds = this.searcher.search(query, num); 
  177.             System.out.println("查詢到的結果數:"+tds.totalHits); 
  178.             for(ScoreDoc sd : tds.scoreDocs){ 
  179.                 doc = this.searcher.doc(sd.doc); 
  180.                 System.out.println("id:"+doc.get("id")+"---"+"name:"+doc.get("name")+"---"+"attachs:"+doc.get("attach")+"---"+"email:"+doc.get("email")); 
  181.             } 
  182.         } catch (IOException e) { 
  183.             // TODO Auto-generated catch block 
  184.             e.printStackTrace(); 
  185.         } finally { 
  186.             try { 
  187.                 this.searcher.close(); 
  188.             } catch (IOException e) { 
  189.                 // TODO Auto-generated catch block 
  190.                 e.printStackTrace(); 
  191.             } 
  192.         } 
  193.     } 
  194.     public void queryByNumericRange(String field,int min,int max,int num, boolean minInclusive, boolean maxInclusive){ 
  195.         Query query = NumericRangeQuery.newIntRange(field, min, max, minInclusive, maxInclusive); 
  196.         try { 
  197.             TopDocs tds = this.searcher.search(query, num); 
  198.             System.out.println("查詢到的結果數:"+tds.totalHits); 
  199.             for(ScoreDoc sd : tds.scoreDocs){ 
  200.                 doc = this.searcher.doc(sd.doc); 
  201.                 System.out.println("id:"+doc.get("id")+"---"+"name:"+doc.get("name")+"---"+"attachs:"+doc.get("attach")+"---"+"email:"+doc.get("email")); 
  202.             } 
  203.         } catch (IOException e) { 
  204.             // TODO Auto-generated catch block 
  205.             e.printStackTrace(); 
  206.         } finally { 
  207.             try { 
  208.                 this.searcher.close(); 
  209.             } catch (IOException e) { 
  210.                 // TODO Auto-generated catch block 
  211.                 e.printStackTrace(); 
  212.             } 
  213.         } 
  214.     } 
  215.  
  216. TestSearchUtil.java 
  217. import org.junit.BeforeClass; 
  218. import org.junit.Test; 
  219.  
  220.  
  221. public class TestSearchUtil { 
  222.      
  223.     static SearchUtil su ; 
  224.     @BeforeClass 
  225.     public static void setUpBeforeClass() throws Exception { 
  226.         su = new SearchUtil(); 
  227.     } 
  228.  
  229.     @Test 
  230.     public void testTermQuery() { 
  231.         su.termQuery("content""hello"5); 
  232.     } 
  233.     @Test 
  234.     public void testTermRangeQuery(){ 
  235.         su.termRangeQuery("name""2""4"5falsefalse); 
  236.     } 
  237.     @Test 
  238.     public void testQueryByNumericRange(){ 
  239.         su.queryByNumericRange("id"3410falsetrue); 
  240.     } 
  241.      

 

本文出自 “Kenan_ITBlog” 博客,請務必保留此出處http://soukenan.blog.51cto.com/5130995/1121975

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章