您的位置:首页 > 其它

Lucene入门例子

2010-07-05 17:05 323 查看
package demo1;
import java.io.File;

import java.io.IOException;

import org.apache.lucene.analysis.standard.StandardAnalyzer;

import org.apache.lucene.document.Document;

import org.apache.lucene.document.Field;

import org.apache.lucene.index.IndexWriter;

import org.apache.lucene.index.Term;

import org.apache.lucene.search.Hits;

import org.apache.lucene.search.IndexSearcher;

import org.apache.lucene.search.TermQuery;
/**

* 实现简单索引的创建

*

* @author Administrator

*

*/

public class Demo1 {
// 索引创建在磁盘的某一个目录下

private final String PATH = "C://index";
public Demo1() {

// TODO Auto-generated constructor stub

}
/**

* 实现创建索引

*/

public void createIndex() {

// new File(PATH)是表示存放索引的路径

// StandardAnalyzer是表示使用Lucece提供的标准分词器进行创建索引

// true 表示覆盖旧的索引 如果为false 表示追加索引

try {

IndexWriter indexWriter = new IndexWriter(new File(PATH),

new StandardAnalyzer(), true);

// 采用手工录入的方式给索引创建内容

// document相当于数据库中表的一行记录

Document doc = new Document();

// title 是表示检索的域 相当于 SQL语句中的 select ename from emp where ???

// Field.Store.YES表示这个内容存储到磁盘中

// Field.Index.TOKENIZED表示创建索引的时候采用分词规则

Field title = new Field("title", "hello world!!", Field.Store.YES,

Field.Index.TOKENIZED);
Document doc2 = new Document();
Field title2 = new Field("title", "hello kity", Field.Store.YES,

Field.Index.TOKENIZED);
doc2.add(title2);

doc.add(title);

indexWriter.addDocument(doc);

indexWriter.addDocument(doc2);

// 对索引进行优化

indexWriter.optimize();

// 关闭索引

indexWriter.close();

System.out.println("创建索引成功!!!");
} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

System.out.println("创建索引失败!!!");

}
}
/**

*

* @param keyWord

* 检索的关键字

*/

public void searchIndex(String keyWord) {

// 表示检索索引是从创建索引的目录开始的。

// 接收用户输入的关键字,用关键字和索引的内容进行匹配,如果找到,则显示

try {
IndexSearcher search = new IndexSearcher(PATH);

// 是按照用户输入的关键字进行检索

Term t = new Term("title", keyWord);
TermQuery tq = new TermQuery(t);

// 检索的结果返回给用户

// hits 相当于我们数据库JDBC中的ResultSet结果集

Hits hits = search.search(tq);
for (int i = 0; i < hits.length(); i++) {
Document doc = (Document) hits.doc(i);
System.out.println("--检索结果是:->>" + doc.get("title"));
}

// 关闭查询

search.close();
} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

System.out.println("检索索引失败!!");

}
}
/**

* @param args

*/

public static void main(String[] args) {

// TODO Auto-generated method stub

Demo1 demo1 = new Demo1();

demo1.createIndex();
demo1.searchIndex("hello");
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: