Lucene的大致結構圖:
信息寫入索引庫的過程:
讀取信息的過程:
下面是一個向索引庫寫入信息與讀取信息的例子:
public void testCreateIndex() throws Exception{ /** * 1、創建一個student對象,並且把信息存放進去 * 2、調用indexWriter的API把數據存放在索引庫中 * 3、關閉indexWriter */ // 創建一個Student對象,並且把信息存放進去 Student student = new Student(); student.setId(1L); student.setName("張三"); // 調用indexWriter的API把數據存放在索引庫中 /** * 創建一個IndexWriter * 參數三個 1、索引庫, 指向索引庫的位置 2、分詞器 */ // 創建索引庫 Directory directory = FSDirectory.open(new File("./indexDir")); // 創建分詞器 Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_30); IndexWriter indexWriter = new IndexWriter(directory, analyzer, MaxFieldLength.LIMITED); // 把一個student對象轉化成document Document document = new Document(); Field idField = new Field("id",student.getId().toString(),Store.YES,Index.NOT_ANALYZED); Field nameField = new Field("name",student.getName(),Store.YES,Index.ANALYZED); document.add(idField); document.add(nameField); indexWriter.addDocument(document); // 關閉indexWriter indexWriter.close(); }
public void testSearchIndex() throws Exception{ /** * 1、創建一個IndexSearch對象 * 2、調用search方法進行檢索 * 3、輸出內容 */ // 創建一個 IndexSearch對象 Directory directory = FSDirectory.open(new File("./indexDir")); IndexSearcher indexSearcher = new IndexSearcher(directory); // 調用search方法進行檢索 Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_30); QueryParser queryParser = new QueryParser(Version.LUCENE_30,"name",analyzer); Query query = queryParser.parse("張"); // 要查找的關鍵詞 TopDocs topDocs = indexSearcher.search(query, 2); // 前兩條 int count = topDocs.totalHits; // 根據關鍵詞查詢出來的總的記錄數 ScoreDoc[] scoreDocs = topDocs.scoreDocs; ListstudentList = new ArrayList (); for(ScoreDoc scoreDoc:scoreDocs){ float score = scoreDoc.score; // 關鍵詞得分 int index = scoreDoc.doc; // 索引的下標 Document document = indexSearcher.doc(index); // 把document轉化成Student Student student = new Student(); student.setId(Long.parseLong(document.get("id"))); // document.getField("id").stringValue() student.setTitle(document.get("name")); studentList.add(student); } for(Student student:studentList){ System.out.println(student.getId()); System.out.println(student.getName()); } }