本文demo視頻觀看地址:http://www.wisdomdd.cn/Wisdom/resource/articleDetail.htm?resourceId=1229
索引的創建
1
2
3
4
5
6
7
8
//指定分詞技術,這裡使用的是標準分詞
Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_43);
//indexWriter的配置信息
IndexWriterConfig indexWriteConfig = new IndexWriterConfig(Version.LUCENE_43, analyzer);
//索引的打開方式:沒有就創建,有就打開
indexWriteConfig.setOpenMode(OpenMode.CREATE_OR_APPEND);
Directory directory = FSDirectory.open(new File("D://index/test"));
IndexWriter indexWrite = new IndexWriter(directory, indexWriteConfig);
1
2
3
4
5
6
7
8
9
10
Document doc1 = new Document();
//StringField域,當成一個整體,不會被分詞
doc1.add(new StringField("id", "abcde", Store.YES));
//TextField域,採用指定的分詞技術
doc1.add(new TextField("content", "極客學院", Store.YES));
//將文檔寫入索引中
indexWrite.addDocument(doc1);
//將indexWrite操作提交,如果不提交,之前的操作將不會保存到硬盤
//但是這一步很消耗系統資源,索引執行該操作需要有一定的策略
indexWrite.commit();
索引的檢索
directory = FSDirectory.open(new File("D://index/test")); //索引硬盤存儲路徑
DirectoryReader dReader = DirectoryReader.open(directory); //讀取索引
IndexSearcher searcher = new IndexSearcher(dReader); //創建索引檢索對象
Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_43); //分詞技術
//創建Query
QueryParser parser = new QueryParser(Version.LUCENE_43, "content", analyzer);
Query query = parser.parse("Lucene案例");
//檢索索引,獲取符合條件的前10條記錄
TopDocs topDocs = searcher.search(query, 10);
閱讀更多 代碼專家 的文章