lucene+paoding親密接觸

來源:互聯網
上載者:User

lucene是什嗎?lucene是一個開源的,廣泛應用的,對資料進行索引、查詢的一個架構,更詳細的介紹請查看www.lucene.com.

 

 

下面簡單的描述一下索引和查詢過程。

1. 做索引簡單過程:

//擷取索引儲存路徑

  String strindexDir = “”;

  File indexDir = new File(strindexDir);

 

 

// 分詞器
  Analyzer analyzer = new PaodingAnalyzer(); // 中文分詞 庖丁解牛

//擷取寫索引對象,準備開始做索引,索引對象相當於資料庫中的表
   indexWriter = new IndexWriter(indexDir, analyzer, true);

//構造Document對象,Document相當於資料庫中 的一條記錄
Document doc = new Document();

 

// 給記錄中的欄位賦值
    doc.add(new Field(“name”, "value", Field.Store.NO, Field.Index.ANALYZED));

    doc.add(new Field(“name”, "value", Field.Store.NO, Field.Index.ANALYZED));

 

//表記錄加入表中
    indexWriter.addDocument(doc);

// 做完索引之後,對索引進行最佳化
   indexWriter.optimize();

 

//關閉資源
   indexWriter.close();

 

2.查詢過程

 

//存放查詢結果
  List<HashMap<String, String>> rs = new ArrayList<HashMap<String, String>>();

 

//擷取分析器,做索引的時候需要分析,查詢的時候也需要分析
  Analyzer analyzer = new PaodingAnalyzer();

 

//構造查詢對象,queryField是查詢那個Field,相當於資料記錄的哪個欄位,q是查詢關鍵字
  query = new QueryParser(queryField, analyzer).parse(q);

//下面這句是可以看到對查詢關鍵字的分析
   System.out.println("query key analyze result: " + query.toString());
 

//擷取索引對象,進行查詢
   IndexReader reader = IndexReader.open(indexDir);
   Searcher searcher = new IndexSearcher(reader);
   Hits hits = searcher.search(query);
   searcher.close();
   

//從查詢結果中擷取資訊
   Document doc = null;

    
    HashMap<String, String> item = new HashMap<String, String>();

    item.put("name", "value");

    item.put("name", "value");
    rs.add(item);

//釋放資源
   reader.close();

 做索引,查詢就被這麼短短几行搞定, 如此看來,lucene好簡單,甚強大。其實不然,要遊刃有餘,需深入磨練。

附上俺的demo。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.