`

Lucene(Lucence)建立索引(字段)

阅读更多
    Lucene,这是官方称谓,也有许多人叫它Lucence,做搜索和分词用的工具包.也有人说是Java下的搜索引擎框架库,见仁见智的说法罢了.不管叫什么,确实非常有用,比如做全站的搜索,其实它的用处远大于此,但凡涉及到文本搜索的地方就能用到它.我们就以做全站搜索为例,演示一下如何应用Lucene建立索引.
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();
    }
  }
}
分享到:
评论
1 楼 yaoyuebar 2008-05-29  
不错,入门写的挺详细的

相关推荐

Global site tag (gtag.js) - Google Analytics