lucene3小例子

公司项目要用到Lucene,首先看了一下最新的版本是3.0,废话不说代码如下

public class Test1 {

public static void main(String[] args) throws SQLException, IOException {
String[] ids = {"1","2","3","4"};
String[] names = {"liujun","aa","bb","cc"};
String[] addresses = {"i am in beijing","nanjing","beijing","aaa"};
String[] birthdays = {"19820203","19840802","19830804","19840806"};

Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_30);

String indexDir = "d:/indexDir";
File f = new File(indexDir);
Directory dir = FSDirectory.open(f);

IndexWriter writer = new IndexWriter(dir,analyzer,true,IndexWriter.MaxFieldLength.LIMITED);

for(int i=0;i<ids.length;i++){
Document d = new Document();
d.add(new Field("id",ids[i],Field.Store.YES,Field.Index.ANALYZED));
d.add(new Field("name",names[i],Field.Store.YES,Field.Index.ANALYZED));
d.add(new Field("address",addresses[i],Field.Store.YES,Field.Index.ANALYZED));
d.add(new Field("birthday",birthdays[i],Field.Store.YES,Field.Index.ANALYZED));

writer.addDocument(d);
}
writer.optimize();
writer.close();
System.out.println("ok");
}

}



这个是把内容索引到Lucene的数据库中



下面开始根据关键字查找

package test;

import java.io.File;
import java.io.IOException;

import org.apache.lucene.document.Document;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

public class Test2 {

/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub

String indexDir = "d:/indexDir";
File f = new File(indexDir);
Directory dir = FSDirectory.open(f);

IndexSearcher searcher = new IndexSearcher(dir);
Term term = new Term("address","beijing");
TermQuery query = new TermQuery(term);
TopDocs topDocs = searcher.search(query, 100);
ScoreDoc[] hits = null;
hits = topDocs.scoreDocs;

for(int i = 0;i<hits.length;i++){
Document doc = searcher.doc(hits[i].doc);
System.out.print(hits[i].score+" ");
System.out.print(doc.get("id")+" ");
System.out.print(doc.get("name")+" ");
System.out.print(doc.get("address")+" ");
System.out.println(doc.get("birthday")+" ");
}
searcher.close();
System.out.println("end");
}

}



因为这样出来之后,不能对中文进行分词,故引用了第三方的包用的是IK Analyzer 3.2.0版本

下载地址

IKAnalyzer3.2.0稳定版发布包 [url]http://ik-analyzer.googlecode.com/files/IKAnalyzer3.2.0Stable_bin.rar[/url]

下面的代码就不贴了



只要照里面的手册改一下就行了

源码里也有一个用到表的例子,索性不改了 直接传
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值