`
meiping
  • 浏览: 47606 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

使用Lucene搭建简单的搜索引擎

    博客分类:
  • Java
阅读更多

假设现有如下格式的记录(Record)
标题(title)
内容(content)
创建时间(mdtime)

现在要求搭建搜索引擎实现在标题和内容字段上进行搜索,同时按照时间倒序排列
 
1.    建索引
      File index = new File("/usr/local/....");              // 索引文件存放目录
      IndexWriter writer = new IndexWriter(index, analyzer); // analyzer是分词器,根据不同的需要选用不同的分词器
                                                             // lucene自带的分词器对中文的支持太弱,网上可以找到中科院分词和IKAnalyzer,另外可以采用目前业界领先的海量分词
      Document document = new Document();
      document.add(new Field("TITLE", title, Field.Store.YES, Field.Index.TOKENIZED));
      document.add(new Field("CONTENT", content, Field.Store.NO, Field.Index.TOKENIZED));
      document.add(new Field("MDTIME", mdtime, Field.Store.YES, Field.Index.UN_TOKENIZED));
 
      writer.addDocument(document);
      writer.optimize();
      writer.close();
 
2.    搜索
      IndexSearcher searcher = new IndexSearcher("/usr/local/....");
      BooleanQuery query = new BooleanQuery();
      QueryParser parser = new QueryParser("TITLE", analyzer);
      // 设置与或关系
      parser.setDefaultOperator(QueryParser.AND_OPERATOR);
      
      // 查询条件
      query.add(parser.parse(title_condition), BooleanClause.Occur.MUST);
      query.add(parser.parse(content_condition), BooleanClause.Occur.MUST);
      
      // 排序
      Hits result = searcher.search(query, new Sort("MDTIME", true));
 
      // 打印结果
      for (int i = 0; i < result.length(); i++) {
          System.out.println(result.doc(i).get("TITLE"));
          System.out.println(result.doc(i).get("CONTENT"));
          System.out.println(result.doc(i).get("MDTIME"));
      }
 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics