ITeye博客

lucene实例(lucene demo)

SmallFish · 2009-04-03 16:15 · Dazhi's · Markdown

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() + "条");
          
        }   
    }   

} 有不明白的地方欢迎联系我,共同探讨

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。