前段时间研究一段时间Lucene,后来因为工作忙,放下了,现在工作闲下来了,重新拿起,发现在Lucene新的版本里变化了不少,现在Lucene的版本是2.4.0,如果不清楚Lucene是什么,就google一下吧。闲话不说,先写个小程序看看。
- package lucene.study.test;
- import java.io.IOException;
- import org.apache.lucene.analysis.Analyzer;
- import org.apache.lucene.analysis.standard.StandardAnalyzer;
- import org.apache.lucene.document.Document;
- import org.apache.lucene.document.Field;
- import org.apache.lucene.index.CorruptIndexException;
- import org.apache.lucene.index.IndexWriter;
- import org.apache.lucene.index.IndexWriter.MaxFieldLength;
- import org.apache.lucene.queryParser.ParseException;
- import org.apache.lucene.queryParser.QueryParser;
- import org.apache.lucene.search.IndexSearcher;
- import org.apache.lucene.search.Query;
- import org.apache.lucene.search.ScoreDoc;
- import org.apache.lucene.search.TopDocs;
- import org.apache.lucene.store.Directory;
- import org.apache.lucene.store.LockObtainFailedException;
- import org.apache.lucene.store.RAMDirectory;
- public class IndexAndSearch {
- public static void main(String[] args) {
- Analyzer analyzer = new StandardAnalyzer();
- //在内存中建立索引
- //也可以使用将索引存储在硬盘上
- //Directory directory = FSDirectory.getDirectory(indexDir);
- Directory directory = new RAMDirectory();
- try {
- IndexWriter iwriter = new IndexWriter(directory,analyzer,true,new MaxFieldLength(2500));
- Document doc = new Document();
- //要被索引的字符串
- String text = "good good study day day up.";
- doc.add(new Field("testIndex",text,Field.Store.YES,Field.Index.ANALYZED));
- iwriter.addDocument(doc);
- iwriter.optimize();
- iwriter.close();
- } catch (CorruptIndexException e) {
- e.printStackTrace();
- } catch (LockObtainFailedException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- //通过索引进行搜索
- try {
- IndexSearcher isearcher = new IndexSearcher(directory);
- QueryParser parser = new QueryParser("testIndex",analyzer);
- Query query = parser.parse("good");
- //在Lucene现在的版本里,原来的返回值为Hits的search方法都置为不推荐方法了
- //而Hits也被TopDocCollector和TopDocs取代了
- //这里的2指的是查询结果中的前两个
- TopDocs tdocs = isearcher.search(query,2);
- ScoreDoc[] sdocs = tdocs.scoreDocs;
- for(int i = 0;i < sdocs.length;i++ ) {
- ScoreDoc sdoc = sdocs[i];
- Document document = isearcher.doc(sdoc.doc);
- System.out.println(document.get("testIndex"));
- }
- } catch (CorruptIndexException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- } catch (ParseException e) {
- e.printStackTrace();
- }
- }
- }
以上是一个简单的索引与查询,建立起初步对Lucene的认识,接下来会体验Lucene强大的索引与查询功能