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

本文介绍如何使用Lucene搭建一个全文搜索引擎,实现对博客标题和内容的高效搜索,并按时间倒序排列搜索结果。文中详细展示了建立索引及搜索的具体步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

假设现有如下格式的记录(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"));
      }
 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值