1. 程式人生 > >lucene4.1多域查詢簡單示例

lucene4.1多域查詢簡單示例

       lucene3.x和之前版本有很大的變動,而lucene4.x版本和lucene3.x也有不小的區別,網上有好多文章,但是差不多都是3.x版本的,在這貼一段程式碼,

從資料庫讀取資料後建立索引,然後根據前臺的關鍵字進行查詢。

//用於存放建立的索引
	String index_Store_Path = "F:\\index";
	Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_41);
	Directory directory = null;
//用於將資料庫的學生資訊建立索引
public void createIndex() throws Exception {
	directory = FSDirectory.open(new File(index_Store_Path));
	IndexWriterConfig indexWriterConfig = new IndexWriterConfig(Version.LUCENE_41,analyzer);
	IndexWriter indexWriter = new IndexWriter(directory,indexWriterConfig);
	
	List<Studentinfo> studentInfos = studentService.searchStus();
	
	for(Studentinfo studentInfo : studentInfos) {
		Document doc = new Document();
		doc.add(new Field("sex",studentInfo.getSex()+"",Store.YES,Index.ANALYZED));
		doc.add(new Field("name",studentInfo.getName()+"",Store.YES,Index.ANALYZED));
		doc.add(new Field("birthday",studentInfo.getBirthday()+"",Store.YES,Index.NOT_ANALYZED));
		doc.add(new Field("nativePlace",studentInfo.getNativePlace()+"",Store.YES,Index.NOT_ANALYZED));
		doc.add(new Field("politicStatus",studentInfo.getPoliticsStatus()+"",Store.YES,Index.NOT_ANALYZED));
		doc.add(new Field("graduatedDep",studentInfo.getGraduatedDep()+"",Store.YES,Index.ANALYZED));
		doc.add(new Field("major",studentInfo.getMajor()+"",Store.YES,Index.ANALYZED));
		doc.add(new Field("degreeLevel",studentInfo.getDegreeLevel()+"",Store.YES,Index.ANALYZED));
		doc.add(new Field("placeOfWork",studentInfo.getPlaceOfWork()+"",Store.YES,Index.ANALYZED));
		doc.add(new Field("administrativeLevel",studentInfo.getAddress()+"",Store.YES,Index.ANALYZED));
		doc.add(new Field("address",studentInfo.getAddress()+"",Store.YES,Index.NOT_ANALYZED));
		doc.add(new Field("postalcode",studentInfo.getPostalcode()+"",Store.YES,Index.NOT_ANALYZED));
		doc.add(new Field("beOnTheJob",studentInfo.getBeOnTheJob()+"",Store.YES,Index.NOT_ANALYZED));
		doc.add(new Field("officePhoneNumber",studentInfo.getOfficePhoneNum()+"",Store.YES,Index.NOT_ANALYZED));
		doc.add(new Field("mobiePhoneNumber",studentInfo.getMobilePhoneNum()+"",Store.YES,Index.NOT_ANALYZED));
		doc.add(new Field("email",studentInfo.getEmail()+"",Store.YES,Index.NOT_ANALYZED));
		
		indexWriter.addDocument(doc);
	}
	indexWriter.close();
}



進行查詢:

public String getStudentInfos() throws Exception {
		
	String keyWord = "";
	String name = new String(stuMiddel.getName().getBytes("iso-8859-1"),"utf8");
	if(!"".equals(name)) {
		keyWord += name;
	}
	String sex = new String(stuMiddel.getSex().getBytes("iso-8859-1"),"utf8");
	if(!"".equals(sex)) {
		keyWord +=" "+sex;
	}
	String graduatedDep = new String(stuMiddel.getGraduatedDep().getBytes("iso-8859-1"),"utf8");
	if(!"".equals(graduatedDep)) {
		keyWord +=" "+graduatedDep;
	}
	String degreeLevel = new String(stuMiddel.getDegreeLevel().getBytes("iso-8859-1"),"utf8");
	if(!"".equals(degreeLevel)) {
		keyWord +=" "+degreeLevel;
	}
	String administrativeLevel = new String(stuMiddel.getAdministrativeLevel().getBytes("iso-8859-1"),"utf8");
	if(!"".equals(administrativeLevel)) {
		keyWord +=" "+administrativeLevel;
	}
	String major = new String(stuMiddel.getMajor().getBytes("iso-8859-1"),"utf8");
	if(!"".equals(major)) {
		keyWord +=" "+major;
	}
	String placeOfWork = new String(stuMiddel.getPlaceOfWork().getBytes("iso-8859-1"),"utf8");
	if(!"".equals(placeOfWork)) {
		keyWord +=" "+placeOfWork;
	}
	String[] fields = new String[]{"name","sex","graduatedDep","administrativeLevel","major","placeOfWork","degreeLevel"};
	
	QueryParser queryParser = new MultiFieldQueryParser(Version.LUCENE_41,fields,analyzer);
	//不加的話預設為or(好像是)
	queryParser.setDefaultOperator(Operator.AND);
	Query query = queryParser.parse(keyWord);
	
    directory = FSDirectory.open(new File(index_Store_Path));

    //獲取訪問索引的介面,進行搜尋        
    IndexReader indexReader  = IndexReader.open(directory);        
    IndexSearcher indexSearcher = new IndexSearcher(indexReader);
    
    //TopDocs 搜尋返回的結果        
    TopDocs topDocs = indexSearcher.search(query, 100);//只返回前100條記錄                
    int totalCount = topDocs.totalHits; // 搜尋結果總數量        
    System.out.println("搜尋到的結果總數量為:" + totalCount);                
    ScoreDoc[] scoreDocs = topDocs.scoreDocs; // 搜尋的結果列表  
    stus = new ArrayList<Studentinfo>();
    
  //把搜尋結果取出放入到集合中        
    for(ScoreDoc scoreDoc : scoreDocs) {            
        int docID = scoreDoc.doc;//當前結果的文件編號            
        float score = scoreDoc.score;//當前結果的相關度得分            
        System.out.println("score is : "+score);                        
        Document document = indexSearcher.doc(docID); 

        Studentinfo	studentInfo = new Studentinfo();            
        studentInfo.setName(document.get("name"));
        studentInfo.setAddress(document.get("address"));
        studentInfo.setAdministrativeLevel(document.get("administrativeLevel"));
        studentInfo.setBirthday(document.get("birthday"));
        studentInfo.setDegreeLevel(document.get("degreeLevel"));
        studentInfo.setEmail(document.get("email"));
        studentInfo.setGraduatedDep(document.get("graduatedDep"));
        studentInfo.setJob(document.get("job"));
        studentInfo.setMajor(document.get("major"));
        studentInfo.setPlaceOfWork(document.get("placeOfWork"));
        studentInfo.setMobilePhoneNum(document.get("mobilePhoneNum"));
        studentInfo.setNativePlace(document.get("nativePlace"));
        studentInfo.setOfficePhoneNum(document.get("officePhoneNum"));
        studentInfo.setPostalcode(document.get("postalcode"));
        studentInfo.setSex(document.get("sex"));
        studentInfo.setBeOnTheJob(document.get("beOnTheJob"));
        stus.add(studentInfo);
    }
    indexReader.close();
    
    return "listStudentInfo";
}


因為資料少,而且剛開始學習lucene,如果有牛人的話,求指點啊.......