论坛首页 Java企业应用论坛

lucene实例(lucene demo)

浏览 3430 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2009-04-03   最后修改:2009-05-16
public class CreateIndex {//建立索引文件
public static void main(String[] args) throws Exception {  
     
        File indexDir = new File("c:\\index"); //索引所在路径 
        Analyzer luceneAnalyzer = new StandardAnalyzer();  
        IndexWriter indexWriter = new IndexWriter(indexDir, luceneAnalyzer, true);       
        long startTime = new Date().getTime();  
        CreateIndexDAO creareindex=new CreateIndexDAO();
        List indexlist=new ArrayList();//数据源      
        indexlist=creareindex.selectData();//
        for (int i = 0; i < indexlist.size(); i++) {
Data data = (Data) indexlist.get(i);
Document doc = new Document();
doc.add(new Field("uid", data.getUid(),
Field.Store.YES, Field.Index.NO));
doc.add(new Field("keyword",data.getKeyword(),
Field.Store.YES,Field.Index.TOKENIZED,Field.TermVector.WITH_POSITIONS_OFFSETS));
doc.add(new Field("txtinfo", data.getTextinfo(),
Field.Store.YES, Field.Index.UN_TOKENIZED));
indexWriter.addDocument(doc);
}
        indexWriter.optimize();
        indexWriter.close();
  
        long endTime = new Date().getTime();  {
        System.out.println("用时" 
                        + (endTime - startTime)  
                        + "秒" 
                       );  
    }  
}
//查询方法
public class CreateSearch {
  public static void main(String[] args) throws IOException, ParseException {  
        Hits hits = null;  
        String queryString = "十";  
        Query query = null;        
        IndexSearcher searcher = new IndexSearcher("c:\\index");    
        Analyzer analyzer = new StandardAnalyzer();  
        try {  
            QueryParser qp = new QueryParser("keyword", analyzer);  
            query = qp.parse(queryString);
       
        } catch (ParseException e) {  
        } 
        if (searcher != null) {  
            hits = searcher.search(query);  
            for (int i = 0; i < hits.length(); i++) {
                Document doc = hits.doc(i);
                String uid = doc.get("uid");
                String keyword = doc.get("keyword");            
                System.out.println("记录:" + keyword + "对应id"+keyword);
            }
          System.out.println("共查出记录" + hits.length() + "条");
         
        }  
    }  
 
}
有不明白的地方欢迎联系我,共同探讨
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics