lucene 小知识
以前对全文检索望而却步,认为很难玩,最近玩了下Lucene ,发现挺容易上手的。废话不多说,记下小体会。
luncen索引用的是倒排索引技术,倒排索引和书后面的索引基本类似。其结构如下图所示:
这种结构使得lucene的检索效率高,在常数时间内一次命中所有的文档,一次I/O操作。
Lucene建立索引非常简单,下面以创建内存索引为例。
首先创建一个内存索引对象:
//建立内存索引对象Directory directory = new RAMDirectory();
//配置IndexWriterConfigIndexWriterConfig iwConfig = new IndexWriterConfig(Version.LUCENE_34 , analyzer);iwConfig.setOpenMode(OpenMode.CREATE_OR_APPEND);IndexWriter iwriter = new IndexWriter(directory , iwConfig);
Document doc = new Document(); doc.add(new Field(fieldName, text, Field.Store.YES, Field.Index.ANALYZED));
iwriter.addDocument(doc); iwriter.close();
IndexReader ireader = IndexReader.open(directory);IndexSearcher isearcher = new IndexSearcher(ireader);String keyword = "要检索的词条";//使用QueryParser查询分析器构造Query对象QueryParser qp = new QueryParser(Version.LUCENE_34, fieldName, analyzer);qp.setDefaultOperator(QueryParser.AND_OPERATOR);Query query = qp.parse(keyword);//搜索相似度最高的5条记录TopDocs topDocs = isearcher.search(query , 5);System.out.println("命中:" + topDocs.totalHits);//输出结果ScoreDoc[] scoreDocs = topDocs.scoreDocs;for (int i = 0; i < topDocs.totalHits; i++){Document targetDoc = isearcher.doc(scoreDocs[i].doc);System.out.println("内容:" + targetDoc.toString());}