posts - 75,comments - 83,trackbacks - 0
1.首先建一个存取值的bean类

package net.xftzr.common;

import java.util.Date;

public class IndexBean {
    
private String indexId;//删除ID
    private String sname;
    
private String ssex;
    
private Date dtDateTime;//  时间
    
    
public IndexBean(){
        
    }
    
public IndexBean(String indexId,String sname,String ssex,Date dtDateTime){
        
this.indexId =indexId;
        
this.sname = sname;
        
this.ssex = ssex;
        
this.dtDateTime = dtDateTime;
    }
    
public String getIndexId() {
        
return indexId;
    }
    
public void setIndexId(String indexId) {
        
this.indexId = indexId;
    }
    
public String getSname() {
        
return sname;
    }
    
public void setSname(String sname) {
        
this.sname = sname;
    }
    
public String getSsex() {
        
return ssex;
    }
    
public void setSsex(String ssex) {
        
this.ssex = ssex;
    }
    
public Date getDtDateTime() {
        
return dtDateTime;
    }
    
public void setDtDateTime(Date dtDateTime) {
        
this.dtDateTime = dtDateTime;
    }
    
}

2.添加索引值的类

package net.xftzr.lucene;

import java.io.File;
import java.util.Date;

import net.xftzr.common.IndexBean;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.DateTools;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexWriter;

public class AddLuceneIndex {
 
public static void main(String arg[])throws Exception{
    
     
//指明要索引文件夹的位置,这里是F盘的S文件夹下  
     File fileDir = new File("f:\\index"); 
     
//对文档内容进行分词处理 把分词内容交给indexWriter建立索引
     Analyzer luceneAnalyzer = new StandardAnalyzer();
     
/**
      * 这条语句创建了类 IndexWriter 的一个实例,该类也是 Lucene 索引机制里面的一个关键类。
      * 这个类能创建一个新的索引或者打开一个已存在的索引并为该所引添加文档。我们注意到该类的构造函数接受三个参数,
      * 第一个参数指定了存储索引文件的路径。第二个参数指定了在索引过程中使用什么样的分词器。最后一个参数是个布尔变量,
      * 如果值为真,那么就表示要创建一个新的索引,如果值为假,就表示打开一个已经存在的索引。
      *  接下来的代码演示了如何添加一个文档到索引文件中。
      * 
*/ 
     IndexWriter indexWriter 
= new IndexWriter(fileDir, luceneAnalyzer, true);
  
     AddLuceneIndex addLuceneIndex 
= new AddLuceneIndex();     
     IndexBean indexBean 
= addLuceneIndex.setIndexBeanValue("1","测试名称1","",new Date());

     Document document 
= new Document();
     
//field 用来描述一个文档的属性  indexID是可被检索的
     Field indexIdFiled = new Field("indexId", indexBean.getIndexId(), Field.Store.YES, Field.Index.TOKENIZED);
     document.add(indexIdFiled);
     
//sname模糊匹配进行分词
     Field snameField = new Field("sname",indexBean.getSname(),Field.Store.YES, Field.Index.TOKENIZED, Field.TermVector.WITH_POSITIONS_OFFSETS);
     document.add(snameField);
     
//时间类型字段
     Date dateTimeValue = indexBean.getDtDateTime();
     Field fieldDateName 
= new Field("dtDateTime", DateTools.dateToString(dateTimeValue, DateTools.Resolution.MILLISECOND), Field.Store.YES, Field.Index.UN_TOKENIZED);
     document.add(fieldDateName);
     Field ssexField 
= new Field("ssex",indexBean.getSsex(),Field.Store.YES,Field.Index.UN_TOKENIZED);
     document.add(ssexField);
     indexWriter.addDocument(document);
     indexWriter.optimize();
     indexWriter.close();
     
 }
 
/**
  * 设置IndexBean类属性的值
  * 
@return
  
*/
 
public IndexBean setIndexBeanValue(String indexId,String sname,String ssex,Date dtDateTime){
     IndexBean indexBean 
= new IndexBean();
     indexBean.setIndexId(indexId);
     indexBean.setSname(sname);
     indexBean.setSsex(ssex);
     indexBean.setDtDateTime(dtDateTime);
     
return indexBean;
 }
}
3.根据条件查询索引文件类

package net.xftzr.lucene;

import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.DateTools;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.Hits;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.Sort;
import org.apache.lucene.search.SortField;

public class QueryLuceneIndex {
    
public static void main(String arg[])throws Exception{
        Analyzer analyzer 
= new StandardAnalyzer();
        IndexSearcher search 
= new IndexSearcher("f:\\index");
        String queryString 
= "测试";
        Query query 
= null;
        Hits hits 
= null;
         
try {   
                 
 //在lucene中有一些字符是被保留来做特殊应用的,它们是:
                   //+  -  &&   ||   !   ( )   { }   [ ]   ^   " ~   *   ?   :   \
                  //但你在查询字符串中需要包含其中的字符的时候,一定要记得在前面加上字符"\"表示转义.
                 //例如要查询:(1+1):2
                //必须写成:\(1\+1\)\:2 

               //TermQuery  skeyWordQuery = new TermQuery(new Term(name, nameValue));//完全匹配查询
              
// BooleanQuery bquery = new BooleanQuery(); //多条件查询

                QueryParser qp = new QueryParser("sname", analyzer); //模糊匹配分词查询  
                query = qp.parse(queryString);   
            } 
catch (ParseException e) {   
            } 
        
if(search!=null){
            
//按序号排序
            SortField SortField1 = new SortField("indexId", SortField.INT, true);  //中间参数表示排序字段类型,true 表示降序 false 升序
            SortField[] sortField_arr = new SortField[]{SortField1};
            Sort sort 
= new Sort(sortField_arr);
            hits 
= search.search(query,sort);
            
if (hits.length() > 0) {  
                
for(int i=0;i<hits.length();i++){
                    Document doc 
= hits.doc(i);
                    System.out.println(
"搜索到的结果1: "+doc.get("sname"));
                    System.out.println(
"搜索到的结果2:"+doc.get("indexId"));
                    DateFormat f 
= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date dateTime 
= DateTools.stringToDate(doc.getField("dtDateTime").stringValue());
                    System.out.println(
"搜索到的结果3:"+f.format(dateTime));                
                }
                
                System.out.println(
"找到:" + hits.length() + " 个结果!");   
            }  
        }
        
    
//       索引中删除文档
//        QueryLuceneIndex queryIndex = new QueryLuceneIndex();
//        queryIndex.deleteLuceneIndex("indexId", "1");
        
      
 
// 修改索引中的文档
       
//针对lucene的索引中文档内容进行修改操作,可以通过先删除后添加实现 

            
    }
    
/**
     * 删除索引文件中的数据
     
*/
    
public void deleteLuceneIndex(String deFieldName,String deFieldNameValue) throws IOException{
        File file 
= new File("f:\\index");
         
/**
         * 从索引中删除文档
         类IndexReader负责从一个已经存在的索引中删除文档
         * 
*/
        IndexReader indexReader 
= IndexReader.open(file);
        indexReader.deleteDocuments(
new Term(deFieldName,deFieldNameValue));
        indexReader.close();
    }
    
}
posted on 2008-12-12 15:48 梓枫 阅读(1727) 评论(2)  编辑  收藏 所属分类: lucene

FeedBack:
# re: lucene查询一个简单的例子
2008-12-12 19:36 | 路人
看不懂,lucene是干什么用的?  回复  更多评论
  
# re: lucene查询一个简单的例子
2008-12-26 15:43 | yanlee
@路人
你猜  回复  更多评论
  

只有注册用户登录后才能发表评论。


网站导航: