lucene多功能搜索

package Java.se.lucene;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.NumericField;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.FuzzyQuery;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.NumericRangeQuery;
import org.apache.lucene.search.PhraseQuery;
import org.apache.lucene.search.PrefixQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TermRangeQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.search.WildcardQuery;
import org.apache.lucene.search.BooleanClause.Occur;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.LockObtainFailedException;
import org.apache.lucene.store.RAMDirectory;
import org.apache.lucene.util.Version;

public class Search {
	private String[] ids={"1","2","3","4","5","6"};
	private String[] emails={"[email protected]","[email protected]",
			"[email protected]","[email protected]","[email protected]","[email protected]"};
	private String[] contents={"i like  gdsfgfds","i like fsdfs","i like fdsfsd",
			"i like fdsfsd","i like like fdfs","i like like like fsefsdfg"};
	private int[] attachs={1,2,3,4,5,6};
	private String[] names={"liwu","zhangsan","xiaoqinag","laona",
			"dabao","lisi"};
	private IndexWriter writer=null;
	private Date[] dates=null;
	private Map<String,Float> scores=new HashMap<String,Float>();
	private Directory directory=null;
	private IndexReader reader=null;
	
	public Search()
	{
		directory=new RAMDirectory();
		setDate();
		index();
	}
	//建立索引
	public void index()
	{
		Document document=null;
         try {
			writer=new IndexWriter(directory, new IndexWriterConfig(Version.LUCENE_36,
				new StandardAnalyzer(Version.LUCENE_36)));
			writer.deleteAll();//更新索引
			for(int i=0;i<ids.length;i++)
			{
				document=new Document();
				document.add(new Field("id", ids[i], 
						Field.Store.YES, Field.Index.NOT_ANALYZED_NO_NORMS  ));
				document.add(new Field("email",emails[i],
						Field.Store.YES,Field.Index.NOT_ANALYZED));
				document.add(new Field("content", contents[i], 
						Field.Store.YES, Field.Index.ANALYZED));
				document.add(new Field("name",names[i],
						Field.Store.YES,Field.Index.NOT_ANALYZED_NO_NORMS));
		    	//为数字添加索引
				document.add(new NumericField("attach", Field.Store.YES,true).
						setIntValue(attachs[i]));
				//为日期添加索引
				document.add(new NumericField("date", Field.Store.YES,true)
				.setLongValue(dates[i].getTime()));//记住要getTime
						
				
		    	String str=emails[i].substring(emails[i].lastIndexOf("@")+1);
		    	//System.out.println(str);
    		    if(scores.containsKey(str))
		    	{
		    		document.setBoost(scores.get(str));
		    	}else{
	    		document.setBoost(0.5f);
		    	}
		    	writer.addDocument(document);
		    	writer.commit();//提交writer
			}
		} 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();
		}
		finally{
            try {
				writer.close();
			} catch (CorruptIndexException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	//获取searcher
	public IndexSearcher getSearcher()
	{
		try {
			if(reader==null)
			{
				reader=IndexReader.open(directory);
			}else {
				IndexReader rd=IndexReader.openIfChanged(reader);
				if(reader!=null)
				{
					reader.close();
					reader=rd;
				}
			}
			return new IndexSearcher(reader);
		} catch (CorruptIndexException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	//词条搜索
	public void searchByQueryParse(Query query,int num)
	{     
		try {
				IndexSearcher searcher=getSearcher();
				TopDocs tds=searcher.search(query, num);
				System.out.println("一共查询了:"+tds.totalHits);
				for(ScoreDoc sd:tds.scoreDocs)
				{
					Document doc=searcher.doc(sd.doc);
					System.out.println(doc.get("id")+"-->"+doc.get("name")+".."
							+"["+doc.get("email")+"]"+"("+doc.get("content")+")"+
							"-->"+doc.get("attach")+".."+doc.get("date"));				
				}			
				searcher.close();
			} catch (CorruptIndexException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}	
	}
	
	//创建日期
    public void setDate()
    {
    	SimpleDateFormat sdf=new SimpleDateFormat("yyyy-mm-kk");
    	try {
    		dates=new Date[ids.length];
        	dates[0]=sdf.parse("2010-08-17");
        	dates[1]=sdf.parse("2011-02-17");
        	dates[2]=sdf.parse("2012-03-17");
        	dates[3]=sdf.parse("2011-04-17");
        	dates[4]=sdf.parse("2012-05-17");
        	dates[5]=sdf.parse("2011-07-17");
		} catch (Exception e) {
			e.printStackTrace();
			// TODO: handle exception
		}
    } 
}

你可能感兴趣的:(lucene多功能搜索)