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,如果有牛人的话,求指点啊.......

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Lucene6 支持多域检索和字段权重设置。在构建 Query 时,可以使用 BooleanQuery 对象来组合多个查询条件,其中每个查询条件可以指定所要检索的字段以及该字段的权重。例如: ``` // 创建查询解析器 QueryParser parser = new MultiFieldQueryParser(fields, analyzer); // 创建查询条件 Query query1 = parser.parse("keyword1"); Query query2 = parser.parse("keyword2"); // 创建 BooleanQuery 对象 BooleanQuery.Builder builder = new BooleanQuery.Builder(); builder.add(query1, Occur.SHOULD).add(query2, Occur.SHOULD); // 设置字段权重 builder.setMinimumNumberShouldMatch(1); builder.add(new BoostQuery(new TermQuery(new Term("field1", "value1")), 2f), Occur.SHOULD); builder.add(new BoostQuery(new TermQuery(new Term("field2", "value2")), 3f), Occur.SHOULD); // 执行查询 IndexSearcher searcher = new IndexSearcher(indexReader); TopDocs topDocs = searcher.search(builder.build(), 10); ``` 在上面的例子中,我们使用了 MultiFieldQueryParser 来创建查询解析器,并指定了要检索的多个字段。然后,我们创建了两个查询条件,并使用 BooleanQuery.Builder 将它们组合起来。在组合查询条件时,我们通过 add() 方法指定了每个查询条件的出现方式(Occur.SHOULD 表示应该出现在结果中,但不是必须的)。接着,我们使用 setMinimumNumberShouldMatch() 方法指定了至少有一个查询条件应该出现在结果中。最后,我们使用 BoostQuery 对象为每个字段设置了不同的权重。在执行查询时,Lucene6 会根据字段权重计算每个文档的得分,并按照得分从高到低排列返回结果。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值