Lucene入门例子

 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");

 }

}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值