- package lucene.test;
- 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.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.Searcher;
- import org.apache.lucene.search.TopDocCollector;
- import org.apache.lucene.store.LockObtainFailedException;
- import org.apache.lucene.store.RAMDirectory;
- public class RAMDirectoryTest {
- public static void main(String[] args) throws ParseException{
- RAMDirectory ramindex=new RAMDirectory();
- try {
- IndexWriter writer=new IndexWriter(ramindex,new StandardAnalyzer(),true,MaxFieldLength.LIMITED);
- writer.addDocument(createDocument("道德经","天地不仁,以万物为刍狗,圣人不仁,以百姓为刍狗。"));
- writer.addDocument(createDocument("大学","大学之道,在明明德,在亲民,在止于至善。"));
- writer.addDocument(createDocument("黄帝内经","恬惔虚无,精神内守;食饮有节,谨和五味。"));
- writer.addDocument(createDocument("中庸","忠恕违道不远,施诸己而不愿,亦勿施于人。"));
- writer.optimize();
- writer.close();
- Searcher searcher=new IndexSearcher(ramindex);
- search(searcher,"德");
- } 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();
- }
- }
- private static void search(Searcher searcher, String queryString) throws ParseException, IOException{
- // TODO Auto-generated method stub
- QueryParser parser=new QueryParser("content",new StandardAnalyzer());
- Query query=parser.parse(queryString);
- int hitsPerPage=100;
- TopDocCollector collector=new TopDocCollector(hitsPerPage);
- searcher.search(query,collector);
- ScoreDoc[] hits=collector.topDocs().scoreDocs;
- int hitCount=hits.length;
- if(hitCount==0){
- System.out.println("没有找到 /""+queryString+"/"");
- }else{
- System.out.println("查找'"+queryString+"'返回"+hitCount+"个结果");
- }
- for(int i=0;i<hits.length;i++){
- int docId=hits[i].doc;
- Document doc=searcher.doc(docId);
- System.out.println("文档编号:"+docId+":"+doc.get("title")+doc.get("content"));
- }
- }
- private static Document createDocument(String title, String content) {
- // TODO Auto-generated method stub
- Document doc=new Document();
- doc.add(new Field("title",title,Field.Store.YES,Field.Index.ANALYZED));
- doc.add(new Field("content",content,Field.Store.YES,Field.Index.ANALYZED));
- return doc;
- }
- }