就搜一条信息!需要一秒!如果按这个速度还不如直接在数据库查呢!!
package com.test.lucene;import java.io.File;import jeasy.analysis.MMAnalyzer;import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.Fieldable;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocCollector;public class LuceneIndex {


public void createIndex(String username,String password,String path){
File f = new File(path);
IndexWriter it = null;

try {
if(f.list()==null){
it = new IndexWriter(path,new MMAnalyzer(),true,IndexWriter.MaxFieldLength.LIMITED);
}else{
it = new IndexWriter(path,new MMAnalyzer(),false,IndexWriter.MaxFieldLength.LIMITED);
}

Document doc = new Document(); 
Fieldable fa = new Field("un",username,Field.Store.YES, Field.Index.NOT_ANALYZED);
Fieldable fa1 = new Field("pw",password,Field.Store.YES, Field.Index.NOT_ANALYZED);
doc.add(fa);
doc.add(fa1);
it.addDocument(doc);
it.optimize();
it.close();
} catch (Exception e) {
e.printStackTrace();


}
public boolean readIndex(String username,String password,String path){
long a = System.currentTimeMillis();
try {

   
   IndexSearcher search = new IndexSearcher(path);
   
   QueryParser parser = new QueryParser("un", new MMAnalyzer());
   
   Query query =parser.parse(username);
   
   TopDocCollector collector = new TopDocCollector(2);   
   search.search(query,collector);
      ScoreDoc[] hits = collector.topDocs().scoreDocs;
      for(int i=0;i<hits.length;i++){
       Document doc = search.doc(hits[i].doc);
     if(username.equals(doc.get("un"))&&password.equals(doc.get("pw"))){
     long b = System.currentTimeMillis();
     System.out.println(b-a);
      return true;
     }
      }       search.close();
} catch (Exception e) {
e.printStackTrace();
}
long b = System.currentTimeMillis();
System.out.println(b-a);
return false;
}
public static void main(String[] args) {
String path = "D:/index";
String username = "xiaosan";
String password = "xieke";
LuceneIndex li = new LuceneIndex();
// li.createIndex(username, password,path);
System.out.println(li.readIndex(username,password,path));
}
}

解决方案 »

  1.   

    Java 深度探索者 高级群: 65670864
    SSH、Ant、IBatis、jsf、seam、portal、设计模式、 
    ZK、DWR、ajax、CSS 、Oracle
      

  2.   

    三楼的说的不错,数据库是处理数据的.!但lucene是专门处理搜索的。他不是在数据库查询,而是在建立的索引中查....hehe 
      

  3.   

    MMAnalyzer这个是什么分词器?不用分词器,直接用term来查询试试
    searcher.Search(new TermQuery(new Term("userName", "你好")));
      

  4.   

    晕了,你的程序运行时,你使用的这些类是加载到内存了,但它们可能还要加载一些其它的类,这些不用时间么?
    任何java程序(也包括其它的程序)的执行时间,不要以第一次执行时间为准,请在第一次执行之后再执行同样的代码记录它的时间(不是重新启动程序,而是重复代码)
    如果不是你的程序问题,建议你对这个查询循环1000次以上