- public void index(List<IArticle> list)
- {
- //IArticle接口提供getName(標題)和getContent(內容)
- //list就是從數據庫里查詢出來的要建立索引的對象的列表
- if(list != null && list.size() > 0)
- {
- try {
- //標記是否重新建立索引,true為重新建立索引
- boolean flag = true;
- //如果已存在索引,則追加索引
- if(IndexReader.indexExists(path))
- {
- flag = false;
- }
- ChineseAnalyzer ca = new ChineseAnalyzer();
- IndexWriter indexWriter = new IndexWriter("c:/lucene/index",ca,flag);
- Document doc = null;
- for(int i=0;i<list.size();i++)
- {
- doc = new Document();
- doc.add(new Field("title",article.getName(),Field.Store.YES,Field.Index.TOKENIZED));
- //添加內容屬性,內容只索引,不存儲
- doc.add(new Field("content",new StringReader(list.get(i).getContent())));
- indexWriter.addDocument(doc);
- }
- //優化并關閉
- indexWriter.optimize();
- indexWriter.close();
- } catch (Exception e)
- {
- // TODO 自動生成 catch 塊
- //e.printStackTrace();
- }
- }
- }
簡單說下需要注意的地方:
1.ChineseAnalyzer ca = new ChineseAnalyzer();這個是分析器,Lucene內置多個,處理中文搜索我會用ChineseAnalyzer.
2.IndexWriter indexWriter = new IndexWriter(c:/lucene/index,ca,true);處理索引的類,注意其構造方法里的最后一個參數,如果為true則表示,下次建立索引時會清除這次建立的索引重新建立索引,如果為false則表示追加索引,在原來索引的基礎上追加.看實際情況定true或false.
3.doc.add(new Field("title",article.getName(),Field.Store.YES,Field.Index.TOKENIZED));這一句表示為文章標題建立索引并存儲.
4.doc.add(new Field("content",new StringReader(list.get(i).getContent())));這句是為內容建立索引但不存儲
這樣我們就為文章對象建立好索引了,然后就可以利用Lucene的其他類對這個索引目錄進行搜索了,關于搜索部分我們稍后再補充上.
下面是搜索部分的代碼,寫的簡陋了點,比較簡單,不再多說,請參看注釋:
- public class Search
- {
- //定義一個索引搜索類對象
- private IndexSearcher searcher = null;
- //定義一個Query對象
- private Query query = null;
- //定義中文分析器
- ChineseAnalyzer analyzer = new ChineseAnalyzer();
- //構造方法里完成searcher的實例化
- public Search()
- {
- try
- {
- //這里的參數就是上面我們生成索引的目錄
- searcher = new IndexSearcher(IndexReader.open("c:/lucene/index"));
- }catch(Exception e)
- {
- e.printStackTrace();
- }
- }
- public Hits search(String keyword) throws Exception
- {
- //開始搜索的時間
- Date start = new Date();
- //對我們索引的content字段進行搜索
- QueryParser qp = new QueryParser("content",analyzer);
- this.query = qp.parse(keyword);
- Hits hits = this.searcher.search(query);
- Date end = new Date();
- System.out.println("檢索完成,用時"+(end.getTime()-start.getTime())+"毫秒");
- //////////打印測試////////
- if(hits != null && hits.length() > 0)
- {
- for(int i = 0; i < hits.length(); i++)
- {
- try
- {
- Document doc = hits.doc(i);
- System.out.println("結果"+(i+1)+":"+doc.get("title")+" createTime:"+doc.get("content"));
- //System.out.println(doc.get("path"));
- }catch(Exception e)
- {
- e.printStackTrace();
- }
- }
- }
- return hits;
- }
- ///調用,主方法
- public static void main(String[] args)
- {
- try
- {
- Search test = new Search();
- Hits h = test.search("你好");
- } catch (Exception e)
- {
- // TODO 自動生成 catch 塊
- e.printStackTrace();
- }
- }
- }
安徽新華電腦學校專業職業規劃師為你提供更多幫助【在線咨詢】