全文檢索索引(二)-基於lucene4.10的增刪改查

來源:互聯網
上載者:User

標籤:lucene   lucene4.10   全文檢索索引   搜尋引擎   增刪改查   

今天 用lucene完成了 一個簡單的web應用,提取了早期編寫的一個測試類別, 首先簡介下lucene幾個常用包;

lucene 包的組成結構:對於外部應用來說索引模組(index)和檢索模組(search)是主要的外部應用入口

org.apache.Lucene.search/ 搜尋入口 
org.apache.Lucene.index/ 索引入口 
org.apache.Lucene.analysis/ 語言分析器 
org.apache.Lucene.queryParser/ 查詢分析器 
org.apache.Lucene.document/ 儲存結構 
org.apache.Lucene.store/  底層IO/儲存結構 
org.apache.Lucene.util/ 一些公用的資料結構 


話不多說,直接上代碼(這是早期封裝的一個測試類別,封裝的還算比較完善,有興趣的朋友可以在此基礎上繼續完善):

package com.lucene.util;import java.io.File;import java.io.IOException;import java.io.StringReader;import java.util.List;import org.apache.log4j.Logger;import org.apache.lucene.analysis.Analyzer;import org.apache.lucene.analysis.TokenStream;import org.apache.lucene.document.Document;import org.apache.lucene.document.Field;import org.apache.lucene.document.StringField;import org.apache.lucene.document.TextField;import org.apache.lucene.document.Field.Store;import org.apache.lucene.index.IndexReader;import org.apache.lucene.index.IndexWriter;import org.apache.lucene.index.IndexWriterConfig;import org.apache.lucene.index.LogDocMergePolicy;import org.apache.lucene.index.LogMergePolicy;import org.apache.lucene.index.Term;import org.apache.lucene.index.IndexWriterConfig.OpenMode;import org.apache.lucene.queryparser.classic.MultiFieldQueryParser;import org.apache.lucene.queryparser.classic.ParseException;import org.apache.lucene.queryparser.classic.QueryParser;import org.apache.lucene.search.IndexSearcher;import org.apache.lucene.search.MatchAllDocsQuery;import org.apache.lucene.search.Query;import org.apache.lucene.search.ScoreDoc;import org.apache.lucene.search.TermQuery;import org.apache.lucene.search.TopDocs;import org.apache.lucene.search.highlight.Highlighter;import org.apache.lucene.search.highlight.InvalidTokenOffsetsException;import org.apache.lucene.search.highlight.QueryScorer;import org.apache.lucene.search.highlight.SimpleFragmenter;import org.apache.lucene.search.highlight.SimpleHTMLFormatter;import org.apache.lucene.store.Directory;import org.apache.lucene.store.FSDirectory;import org.apache.lucene.util.NumericUtils;import org.apache.lucene.util.Version;import org.wltea.analyzer.lucene.IKAnalyzer;import com.message.base.search.SearchBean;/** * lucene 4.10.1 *  * @creatTime 2014-10-28 * @author 胡慧超 *  */public class HhcIndexTools {private final static Logger logger = Logger.getLogger(HhcIndexTools.class);private static String indexPath = "E://lucene//index";public static void main(String[] args) {try {//createIndex();//searchIndex("碼農");//query();//deleteIndex(null);forceDeleteIndex();query();highlighterSearch();} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}/** * 建立索引 */public static void createIndex() {// 最細粒切分演算法--true的話是 智能切分Analyzer analyzer = new IKAnalyzer(false);Document doc = null;IndexWriter indexWriter = null;try {indexWriter = getIndexWriter(analyzer);// 添加索引doc = new Document();doc.add(new StringField("id", "1", Store.YES));doc.add(new TextField("title", "標題:開始", Store.YES));doc.add(new TextField("content", "內容:我現在是個碼農", Store.YES));indexWriter.addDocument(doc);doc = new Document();doc.add(new StringField("id", "2", Store.YES));doc.add(new TextField("title", "標題:結束", Store.YES));doc.add(new TextField("content", "內容:我現在是個lucene開發工程師的專家",Store.YES));indexWriter.addDocument(doc);indexWriter.commit();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();logger.info("索引器發送異常");} finally {try {destroyWriter(indexWriter);} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}/** * 搜尋文檔 *  * @param keyword */@SuppressWarnings("deprecation")public static void searchIndex(String keyword) {IndexReader indexReader = null;IndexSearcher indexSearcher = null;try {// 1.建立Directory 在硬碟上的F:/luence/index下建立索引Directory dir = FSDirectory.open(new File(indexPath));// 2.建立IndexReaderindexReader = IndexReader.open(dir);// 執行個體化搜尋器indexSearcher = new IndexSearcher(indexReader);// 使用QueryParser查詢分析器構造Query對象QueryParser parse = new QueryParser(Version.LUCENE_4_10_1,"content", new IKAnalyzer(false));// 搜尋包含keyword關鍵字的文檔Query query = parse.parse(keyword.trim());// 使用lucene構造搜尋引擎的時候,如果要針對多個域進行一次性查詢// 這種方法的好處就是可以加權給欄位的控制// 在這四個域中檢索String[] fields = { "phoneType", "name", "category", "price" };Query querys = new MultiFieldQueryParser(Version.LATEST, fields,new IKAnalyzer(false)).parse(keyword.trim());TopDocs results = indexSearcher.search(query, 1000);// 6.根據TopDocs擷取ScoreDoc對象ScoreDoc[] score = results.scoreDocs;if (score.length > 0) {logger.info("查詢結果數:" + score.length);System.out.println("查詢結果數:" + score.length);for (int i = 0; i < score.length; i++) {// 7.根據Seacher和ScoreDoc對象擷取具體的Document對象Document doc = indexSearcher.doc(score[i].doc);// 8.根據Document對象擷取需要的值System.out.println(doc.toString());System.out.println(doc.get("title") + "["+ doc.get("content") + "]");}} else {}} catch (Exception e) {// TODO: handle exceptionlogger.info("查詢結果為空白!");} finally {if (indexReader != null) {try {indexReader.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}/** * 對搜尋返回的前n條結果進行分頁顯示 *  * @param keyWord *            查詢關鍵詞 * @param pageSize *            每頁顯示記錄數 * @param currentPage *            當前頁 * @throws ParseException */@SuppressWarnings("deprecation")public void paginationQuery(String keyWord, int pageSize, int currentPage)throws IOException, ParseException {String[] fields = { "title", "content" };QueryParser queryParser = new MultiFieldQueryParser(Version.LATEST,fields, new IKAnalyzer());Query query = queryParser.parse(keyWord.trim());IndexReader indexReader = IndexReader.open(FSDirectory.open(new File(indexPath)));IndexSearcher indexSearcher = new IndexSearcher(indexReader);// TopDocs 搜尋返回的結果TopDocs topDocs = indexSearcher.search(query, 100);// 只返回前100條記錄TopDocs all = indexSearcher.search(new MatchAllDocsQuery(), 100);// int totalCount = topDocs.totalHits; // 搜尋結果總數量ScoreDoc[] scoreDocs = topDocs.scoreDocs; // 搜尋返回的結果集合// 查詢起始記錄位置int begin = pageSize * (currentPage - 1);// 查詢終止記錄位置int end = Math.min(begin + pageSize, scoreDocs.length);// 進行分頁查詢for (int i = begin; i < end; i++) {int docID = scoreDocs[i].doc;System.out.println("docID=" + docID);Document doc = indexSearcher.doc(docID);String title = doc.get("title");System.out.println("title is : " + title);}indexReader.close();}@SuppressWarnings("deprecation")public static void highlighterSearch() throws IOException, ParseException, InvalidTokenOffsetsException {IndexReader reader = IndexReader.open(FSDirectory.open(new File(indexPath)));IndexSearcher searcher = new IndexSearcher(reader);// String []fields={"title","content"};// QueryParser parser=new MultiFieldQueryParser(Version.LATEST, fields,// new IKAnalyzer());// Query query=parser.parse("");Term term = new Term("content", "lucene");TermQuery query = new TermQuery(term);TopDocs topdocs = searcher.search(query, Integer.MAX_VALUE);ScoreDoc[] scoreDoc = topdocs.scoreDocs;System.out.println("查詢結果總數:" + topdocs.totalHits);System.out.println("最大的評分:" + topdocs.getMaxScore());for(int i=0;i<scoreDoc.length;i++){int docid=scoreDoc[i].doc;Document document=searcher.doc(docid);System.out.println("============檔案【"+(i+1)+"】=========");System.out.println("檢索關鍵字:"+term.toString());String content=document.get("content");//高亮展示 SimpleHTMLFormatter //SimpleHTMLFormatter  formatter=new SimpleHTMLFormatter("<font color='red'>", "</font>");Highlighter highlighter=new Highlighter(formatter, new QueryScorer(query));        highlighter.setTextFragmenter(new SimpleFragmenter(content.length()));                 if(!"".equals(content)){        TokenStream tokenstream=new IKAnalyzer().tokenStream(content, new StringReader(content));        String highLightText = highlighter.getBestFragment(tokenstream,content);              System.out.println("高亮顯示第 " + (i + 1) + " 條檢索結果如下所示:");              System.out.println(highLightText);             /*End:結束關鍵字高亮*/            System.out.println("檔案內容:"+content);                        System.out.println("匹配相關度:"+scoreDoc[i].score);        }}}/** * 擷取indexWriter對象---擷取索引器 *  * @param dir * @param analyer * @return * @throws IOException */private static IndexWriter getIndexWriter(Analyzer analyzer)throws IOException {File indexFile = new File(indexPath);if (!indexFile.exists())indexFile.mkdir();// 索引庫不存在 則建立一個Directory directory = FSDirectory.open(indexFile);// Directory directory = new RAMDirectory(); //在記憶體中建立索引IndexWriterConfig conf = new IndexWriterConfig(Version.LUCENE_4_10_1,analyzer);LogMergePolicy mergePolicy = new LogDocMergePolicy();// 索引基本配置// 設定segment添加文檔(Document)時的合并頻率// 值較小,建立索引的速度就較慢// 值較大,建立索引的速度就較快,>10適合批量建立索引mergePolicy.setMergeFactor(30);// 設定segment最大合并文檔(Document)數// 值較小有利於追加索引的速度// 值較大,適合批量建立索引和更快的搜尋mergePolicy.setMaxMergeDocs(5000);conf.setMaxBufferedDocs(10000);conf.setMergePolicy(mergePolicy);conf.setRAMBufferSizeMB(64);conf.setOpenMode(OpenMode.CREATE_OR_APPEND);if (IndexWriter.isLocked(directory)) {// ?IndexWriter.unlock(directory);}IndexWriter indexWriter = new IndexWriter(directory, conf);return indexWriter;}/** * 銷毀writer *  * @param writer * @throws IOException */private static void destroyWriter(IndexWriter indexWriter)throws IOException {if (indexWriter != null) {indexWriter.close();}}/** * 大量刪除 *  * @param list * @throws IOException */public static void deleteIndexs(List<SearchBean> list) throws IOException {if (list == null || list.size() > 0) {logger.debug("beans is null");return;}for (SearchBean bean : list) {deleteIndex(bean);}}/** * 刪除單個索引 --不會立刻刪除,產生.del檔案 *  * @param bean * @throws IOException */private static void deleteIndex(SearchBean bean) throws IOException {// if(bean==null){// logger.debug("Get search bean is empty!");// return;// }IndexWriter indexWriter = getIndexWriter(new IKAnalyzer());// 參數是一個選項,可以是一個Query,也可以是一個term,term是一個精確尋找的值// 這裡刪除id=1的文檔,還會留在”資源回收筒“。xxx.delindexWriter.deleteDocuments(new Term("id", "1"));destroyWriter(indexWriter);}/** * 查詢文檔 */@SuppressWarnings("deprecation")public static void query() {// 1.建立Directory 在硬碟上的F:/luence/index下建立索引try {IndexReader indexReader = IndexReader.open(FSDirectory.open(new File(indexPath)));System.out.println("儲存的文檔數:" + indexReader.numDocs());System.out.println("總儲存量:" + indexReader.maxDoc());System.out.println("被刪除的文檔:" + indexReader.numDeletedDocs());} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}/** * 復原資源回收筒 *  * @throws IOException */public void recoveryIndexByIsDelete() throws IOException {IndexWriter indexWriter = getIndexWriter(new IKAnalyzer());indexWriter.rollback();destroyWriter(indexWriter);}/** * 清空資源回收筒 在版本3.6之後,已經沒有了unDeleteAll()方法了 *  * @throws IOException */public static void forceDeleteIndex() throws IOException {IndexWriter indexWriter = getIndexWriter(new IKAnalyzer());indexWriter.forceMergeDeletes();destroyWriter(indexWriter);}/** * 更新索引 *  * @throws IOException */public void update() throws IOException {IndexWriter indexWriter = new IndexWriter(FSDirectory.open(new File(indexPath)), new IndexWriterConfig(Version.LATEST,new IKAnalyzer(true)));Document document = new Document();document.add(new Field("id", "10", Field.Store.YES,Field.Index.NOT_ANALYZED_NO_NORMS));document.add(new Field("email", "9481629991", Field.Store.YES,Field.Index.NOT_ANALYZED));document.add(new Field("name", "小米", Field.Store.YES,Field.Index.NOT_ANALYZED_NO_NORMS));document.add(new Field("content", "小米好", Field.Store.NO,Field.Index.ANALYZED));// 這裡的更新,從方法上可以看出,它實際上時將舊的刪除,然後添加一個新文檔的進去,將匹配到term的文檔刪除,然後就新的document添加進去indexWriter.updateDocument(new Term("id", "1"), document);indexWriter.close();}}



全文檢索索引(二)-基於lucene4.10的增刪改查

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.