Lucene的總體架構——基于Lucene7.0

前言:根據Lucene7.0版本介紹Lucene相關知識

總體架構

在Lucene in action中,Lucene 的構架和過程如下圖,


Lucene in action 中Lucene架構

根據Lucene架構圖,lucene主要包含兩個過程,建立索引以及搜索索引。

  • 建立索引
    使用Lucene時,將被搜索的內容包括文件、數據庫、web數據等數據源轉換成lucene的Document對象,存入系統文件或內存中,建立索引。
  • 搜索索引
    當用戶搜索時,將用戶搜索內容封裝成Query對象,并通過search函數搜索Lucene索引,如果命中關鍵詞,則返回命中的TopDocs對象

具體代碼(Lucene7.0)

 public void buildIndex() {
        try {
            //索引建立過程
            //創建索引目錄,RAMDirectory基于內存
            RAMDirectory directory = new RAMDirectory();
            //保存用于創建IndexWriter對象的所有配置;WhitespaceAnalyzer空白分詞器,用于建立索引時的分詞
            IndexWriterConfig config = new IndexWriterConfig(new WhitespaceAnalyzer());
            //創建IndexWriter用于建立索引
            IndexWriter indexWriter = new IndexWriter(directory, config);
            //Document索引的載體,每條索引信息對應一個document對象
            Document document = new Document();
            //Field對象相當于索引信息的某個屬性,通過add()添加到document中,StringField的value作為一個整體,不能再被分詞;第三個參數代表是否被存儲
            document.add(new StringField("name", "seansherwood", Field.Store.YES));
            //TextField中的值需要被分詞器分詞
            document.add(new TextField("description", "like Android and Lucene", Field.Store.YES));
            //建立索引
            indexWriter.addDocument(document);
            //建立索引之后要將indexWriter對象commit方法,對于索引的增刪改操作都需要進行commit;如果建立索引完成可以直接調用close,其默認調用了commit
            indexWriter.close();
            //搜索過程
            //IndexSearcher用于索引搜索,參數需要創建索引時的索引目錄
            IndexSearcher searcher = new IndexSearcher(DirectoryReader.open(directory));
            //封裝搜索查詢語句
            Query query = new TermQuery(new Term("description", "Lucene"));
            //搜索返回命中的document的ID對象
            TopDocs hit = searcher.search(query, 10);
            System.out.println(hit.scoreDocs.length);
            //遍歷拿到索引中的document
            for (int i = 0; i < hit.scoreDocs.length; i++) {
                Document doc = searcher.doc(hit.scoreDocs[i].doc);
                System.out.println("name:" + doc.get("name"));
                System.out.println("description:" + doc.get("description"));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

注:能力一般,水平有限,如有不當之處,請批評指正,定當虛心接受!

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容