Lucene 3.5 测试代码

今天看Oracle的全文索引功能,突发奇想想自己写个搜索程序,在网上下到Lucene后首先当然是测试代码了,没想到网上的教程都很旧了,最新3.5版中有不少接口都废弃了,在网上找到的3.5的代码又都比较复杂,于是干脆看了几个小时文档,自己写出来一个逻辑简单的测试代码。

本人环境:winduws 7 sp1 64 bit,java 6u30 64 bit,eclipse 3.7.1 64 bit

package LiuIndex;

import java.io.IOException;

import org.apache.lucene.document.*;
import org.apache.lucene.analysis.*;
import org.apache.lucene.analysis.standard.*;
import org.apache.lucene.index.*;
import org.apache.lucene.queryParser.*;
import org.apache.lucene.search.*;
import org.apache.lucene.store.*;
import org.apache.lucene.util.*;

public class Main {

public static void main(String[] args) throws CorruptIndexException,
LockObtainFailedException, IOException, ParseException {
//创建索引优化器
Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_35);
//创建索引文件夹,此处试验,创建为内存文件夹
Directory directory = new RAMDirectory();
//创建索引写入器
IndexWriter iwriter = new IndexWriter(directory, new IndexWriterConfig(
Version.LUCENE_35, analyzer));
//创建Document
Document doc = new Document();
//创建被索引文件,此处使用文本
String text = "This is the text to be indexed.";
//开始创建索引
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);
//创建查询转换器
QueryParser parser = new QueryParser(Version.LUCENE_35, "fieldname",
analyzer);
//文本转换为引擎识别代码
Query query = parser.parse("text");
ScoreDoc[] hits = isearcher.search(query, null, 1000).scoreDocs;
System.out.println(hits.length);
//完成查询
for (int i = 0; i < hits.length; i++) {
Document hitDoc = isearcher.doc(hits[i].doc);
System.out.println(hitDoc.get("fieldname"));
}
isearcher.close();
ireader.close();
directory.close();
}
}

以上。

你可能感兴趣的:(Lucene 3.5 测试代码)