private static final path="c:\\index";
Document doc1=new Document(); //要進行索引的單元,任何可以想要被索引的文件都必須轉化為Document對象才能進行索引。
doc1.add(new Field("name","lighter javaeye com",Field.Store.Yes,Field.Index.TOKENIZED));
Document doc2=new Document();
doc2.add(new Field("name","daniel java eye com",Field.Store.YES,Field.Index.TOKENIZED));//Field字段
IndexWriter writer=new IndexWriter(FSDirectory.getDirecotory(path,true),new StandardAnalyzer(),ture); //FSDirectory.getDirecotory(path,true)索引存放的位置,沒有就create;StandardAnalyzer是分析器,主要用于分析搜索引擎遇到的各種文本。常用的有StandardAnalyzer分析器、
writer.setMaxFieldLength(3);
writer.addDocument(doc1); //將文檔加入索引
writer.setMaxFieldLength(3);
writer.addDocument(doc2);//將文檔加入索引
writer.close();
IndexSearcher searcher=new IndexSearcher(path); //檢索工具。指定路徑
Hits hits =null; //搜索返回結果
Query query=null; //查詢
QueryParser qp=new QueryParser("name",new StandardAnalyzer()); //一個解析用戶輸入的工具,可以通過掃描用戶輸入的字符串,生成Query對象。
query=qp.parser("java");
hits=searcher.search(query);
System.out.println(hits.length());
query=qp.parser("daniel");
hits=searcher.search(query);
System.out.println("搜索的個數:"+hits.length());