虽然lucene3.0都出来了,但是相比较lucene2.4.1的文档更全面一些,所有现在还是用lucene2.4.1
创建lucene的类
/**
*类说明
*@author kaowww153
*@version 1.0 创建时间: Apr 27, 2010 11:17:49 AM
**/
@Service
public class LuceneTestService {
@Autowired
private UserDao userDao;
/**
* 方法描述:测试数据
* @return
*/
public List<User> getUsers(){
List<User> users = userDao.findAll();
return users;
}
/**
* 方法描述:
*/
public void getLuceneIndex(){
List<User> users = getUsers();
IndexWriter indexWriter;
try {
//构造函数参数:索引目录,分词类型,是否创建目录,limited 字段默认最大长度10000 unlimited 没有长度限制
indexWriter = new IndexWriter("d:/index/ii",new StandardAnalyzer(),true,MaxFieldLength.LIMITED);
//遍历user放到document里面
Document document = null;
for(User user : users){
document =new Document();
//字段名字,字段值,字段是否保存到index,是否对字段进行分词
document.add(new Field("uid", user.getUid().toString(), Field.Store.YES, Field.Index.ANALYZED));
document.add(new Field("username", user.getUsername(), Field.Store.YES, Field.Index.ANALYZED));
indexWriter.addDocument(document);
}
indexWriter.optimize();
indexWriter.close();
} catch (CorruptIndexException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (LockObtainFailedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 方法描述:得到搜索lucene的值
* @param queryName
* @return
*/
public ScoreDoc[] getResultByLucene(String queryName) {
getLuceneIndex();
IndexSearcher indexSearcher;
try {
File file = new File("d:/index/ii");
FSDirectory fsdir = FSDirectory.getDirectory(file);
indexSearcher = new IndexSearcher(fsdir);
//字段是否必须出现
Occur[] flags = {BooleanClause.Occur.SHOULD};
//可以选择多个搜索的字段
Query query = MultiFieldQueryParser.parse(queryName,new String[]{"username"}, flags, new StandardAnalyzer());
// QueryParser queryParser = new QueryParser("username",new PaodingAnalyzer());
// Query query = queryParser.parse(queryName);
TopDocCollector collector = new TopDocCollector(10);
indexSearcher.search(query,collector);
//符合关键字的document
ScoreDoc[] hits = collector.topDocs().scoreDocs;
return hits;
} catch (CorruptIndexException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
采用junit测试
@ContextConfiguration(locations = {"/applicationContext*.xml"})
public class UserServiceTest extends AbstractTransactionalJUnit4SpringContextTests {
@Autowired
private LuceneTestService luceneService;
@Test
public void test() {
ScoreDoc[] hits = luceneService.getResultByLucene("qeqw 111");
System.out.println(hits.length);
}
}
房改房