一个例子学懂搜索引擎(lucene)

其实,lucene是一个很容易上手的搜索引擎框架,传统的搜索引擎,涉及到爬虫,也就是爬取网页,然后对 网页进行加工,也就是索引,最后用于搜索,lucene这个框架可以很方便的帮你做到后面两个步骤,也就是索引和搜索!本文尝试通过一个例子,使大家掌握 lucene的使用核心方法,包括分词、索引、搜索不同的目录、搜索不同的域,希望大家通过这个实例,对lucene和搜索引擎能有比较全面的认识!

<script type="text/javascript"> var content=document.getElementById("content"); var contentArray=content.innerHTML.split("page@"); var total=contentArray.length; //总条目: 可变 //取得当前页序号 - idx idx=window.location.href; //这里得到 ?0 字样 //动态的分页用到的 staticidx=window.location.search; //这里得到 ?0 字样 //静态的分页用到的 if(staticidx=="") staticidx="?0"; else{ idx+="&pageid=0"; } mylen=idx.length-1; idcontent=idx.substr(mylen,idx.length); staticidxmylen=staticidx.length-1; staticidxidcontent=staticidx.substr(staticidxmylen,staticidx.length); idcontentx=idx.substr(0,mylen); function echostr(pg) { //函数: 打印各页内容 var mystr=""; if(contentArray[pg]) mystr+=contentArray[pg]; if(pg>=contentArray.length) mystr+=contentArray[0]; document.write(mystr); } if(staticidx.length=2)echostr(staticidxidcontent); //显示页面内容 ,判断静态的是2的时候采用输出 else echostr(idcontent); function pg_link(all){ //函数: 打印页码链接 linkstr="<br>第 "; for(i=0;i<all;i++) { j=i+1; if(staticidx.length==2){ i!=staticidxidcontent ? linkstr+="<a href='?" + i + "'>" + j + "</a> ":linkstr+=j + " "; } else{ i!=idcontent ? linkstr+="<a href='"+idcontentx+i+ "'>" + j + "</a> ":linkstr+=j + " "; } } linkstr+="页"; if(all!=1) document.write("<div align='right'>"+linkstr + "</div><br><br>"); else document.write(""); } pg_link(total); //显示页码链接 </script>

其实,lucene是一个很容易上手的搜索引擎框架,传统的搜索引擎,涉及到爬虫,也就是爬取网页,然后对网页进行加工,也就是 索引,最后用于搜 索,lucene这个框架可以很方便的帮你做到后面两个步骤,也就是索引和搜索!本文尝试通过一个例子,使大家掌握lucene的使用核心方法,包括分 词、索引、搜索不同的目录、搜索不同的域,希望大家通过这个实例,对lucene和搜索引擎能有比较全面的认识!

下面是这个例子的代码:
phz.LuceneTest.java

 
  1. package  phz;
  2.  
  3. import  org.apache.lucene.analysis.standard.StandardAnalyzer;
  4. import  org.apache.lucene.document.Document;
  5. import  org.apache.lucene.document.Field;
  6. import  org.apache.lucene.index.IndexWriter;
  7. import  org.apache.lucene.queryParser.MultiFieldQueryParser;
  8. import  org.apache.lucene.search.BooleanClause;
  9. import  org.apache.lucene.search.Hits;
  10. import  org.apache.lucene.search.IndexSearcher;
  11. import  org.apache.lucene.search.MultiSearcher;
  12. import  org.apache.lucene.search.Query;
  13.  
  14. /**
  15.  * 这个实例包含了lucene所有核心用法
  16.  *
  17.  * @author panhuizi
  18.  *
  19.  */
  20. public   class  LuceneTest {
  21.  
  22.     public   static   void  main(String[] args) {
  23.         try  {
  24.             LuceneTest luceneTest = new  LuceneTest();
  25.             // 创建索引
  26.             luceneTest.index();
  27.             // 在索引所在目录下搜索"中国 金牌"
  28.             luceneTest.search("中国 金牌" );
  29.         } catch  (Exception e) {
  30.             e.printStackTrace();
  31.         }
  32.         System.out.println("ok" );
  33.     }
  34.  
  35.     public   void  index()  throws  Exception {
  36.         /* 创建索引初始化,执行这些语句将创建或清空d://save//目录下所有索引 */
  37.         IndexWriter writer1 = new  IndexWriter( "d://save//" ,
  38.                 new  StandardAnalyzer(),  true );
  39.         writer1.close();
  40.  
  41.         /*
  42.          * 往创建的初始化索引中添加索引内容,StandardAnalyzer表示用lucene自带的标准分词机制,
  43.          * false表示不覆盖原来该目录的索引,细心的读者可能已经发现, 这句话和上面的那句就这个false不一样
  44.          */
  45.         IndexWriter writer2 = new  IndexWriter( "d://save//" ,
  46.                 new  StandardAnalyzer(),  false );
  47.         /* 创建一份文件 */
  48.         Document doc1 = new  Document();
  49.         /*
  50.          * 创建一个域ArticleTitle,并往这个域里面添加内容 "Field.Store.YES"表示域里面的内容将被存储到索引
  51.          * "Field.Index.TOKENIZED"表示域里面的内容将被索引,以便用来搜索
  52.          */
  53.         Field field1 = new  Field( "ArticleTitle""北京2008年奥运会" , Field.Store.YES,
  54.                 Field.Index.TOKENIZED);
  55.         /* 往文件里添加这个域 */
  56.         doc1.add(field1);
  57.         /* 同理:创建另外一个域ArticleText,并往这个域里面添加内容 */
  58.         Field field2 = new  Field( "ArticleText""这是一届创造奇迹、超越梦想的奥运会......." ,
  59.                 Field.Store.YES, Field.Index.TOKENIZED);
  60.         doc1.add(field2);
  61.         // 在这里还可以添加其他域
  62.         /* 添加这份文件到索引 */
  63.         writer2.addDocument(doc1);
  64.  
  65.         /* 同理:创建第二份文件 */
  66.         Document doc2 = new  Document();
  67.         field1 = new  Field( "ArticleTitle""中国获得全球赞誉" , Field.Store.YES,
  68.                 Field.Index.TOKENIZED);
  69.         doc2.add(field1);
  70.         field2 = new  Field( "ArticleText""中国所取得的金牌总数排行榜的榜首........" ,
  71.                 Field.Store.YES, Field.Index.TOKENIZED);
  72.         doc2.add(field2);
  73.  
  74.         writer2.addDocument(doc2);
  75.  
  76.         // 在这里可以添加其他文件
  77.  
  78.         /* 关闭 */
  79.         writer2.close();
  80.     }
  81.  
  82.     public   void  search(String serchString)  throws  Exception {
  83.         /* 创建一个搜索,搜索刚才创建的d://save//目录下的索引 */
  84.         IndexSearcher indexSearcher = new  IndexSearcher( "d://save//" );
  85.         /* 在这里我们只需要搜索一个目录 */
  86.         IndexSearcher indexSearchers[] = { indexSearcher };
  87.         /* 我们需要搜索两个域"ArticleTitle", "ArticleText"里面的内容 */
  88.         String[] fields = { "ArticleTitle""ArticleText"  };
  89.         /* 下面这个表示要同时搜索这两个域,而且只要一个域里面有满足我们搜索的内容就行 */
  90.         BooleanClause.Occur[] clauses = { BooleanClause.Occur.SHOULD,
  91.                 BooleanClause.Occur.SHOULD };
  92.         /*
  93.          * MultiFieldQueryParser表示多个域解析,
  94.          * 同时可以解析含空格的字符串,如果我们搜索"中国 金牌",根据前面的索引,显然搜到的是第二份文件
  95.          */
  96.         Query query = MultiFieldQueryParser.parse(serchString, fields, clauses,
  97.                 new  StandardAnalyzer());
  98.         /* Multisearcher表示多目录搜索,在这里我们只有一个目录 */
  99.         MultiSearcher searcher = new  MultiSearcher(indexSearchers);
  100.         /* 开始搜索 */
  101.         Hits h = searcher.search(query);
  102.         /* 把搜索出来的所有文件打印出来 */
  103.         for  ( int  i =  0 ; i < h.length(); i++) {
  104.             /* 打印出文件里面ArticleTitle域里面的内容 */
  105.             System.out.println(h.doc(i).get("ArticleTitle" ));
  106.             /* 打印出文件里面ArticleText域里面的内容 */
  107.             System.out.println(h.doc(i).get("ArticleText" ));
  108.         }
  109.         /* 关闭 */
  110.         searcher.close();
  111.     }
  112. }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
当然可以。Lucene一个强大的全文检索引擎,它提供了很多评分算法,可以根据不同的需求进行选择。在这里,我将为您提供一个使用自定义评分算法的Java代码示例。 首先,您需要创建一个自定义评分算法类。让我们称之为“CustomScoreProvider”。以下是一个基本的实现: ```java import org.apache.lucene.index.IndexReader; import org.apache.lucene.search.Explanation; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.function.CustomScoreProvider; public class CustomScoreProvider extends CustomScoreProvider { public CustomScoreProvider(IndexReader reader) { super(reader); } @Override public float customScore(int doc, float subQueryScore, float valSrcScore) { // 在这里实现您的评分算法 // 这个例子简单地将子查询的得分和值源得分相加 return subQueryScore + valSrcScore; } @Override public Explanation customExplain(int doc, Explanation subQueryExpl, Explanation valSrcExpl) { // 在这里实现您的解释算法 // 这个例子简单地将子查询的解释和值源的解释组合起来 Explanation expl = new Explanation( customScore(doc, subQueryExpl.getValue(), valSrcExpl.getValue()), "custom score: sum of subQueryScore and valSrcScore"); expl.addDetail(subQueryExpl); expl.addDetail(valSrcExpl); return expl; } } ``` 然后,您需要创建一个“CustomScoreQuery”类,以便使用自定义评分算法。以下是一个基本的实现: ```java import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.TopDocs; import org.apache.lucene.search.function.CustomScoreQuery; public class CustomScoreQuery extends CustomScoreQuery { public CustomScoreQuery(Query subQuery) { super(subQuery); } @Override public CustomScoreProvider getCustomScoreProvider(IndexReader reader) { // 创建并返回自定义评分提供程序 return new CustomScoreProvider(reader); } } ``` 现在,您可以使用“CustomScoreQuery”来执行搜索并使用自定义评分算法进行排序。以下是一个基本示例: ```java import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.document.TextField; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriterConfig; import org.apache.lucene.index.Term; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.TermQuery; import org.apache.lucene.store.Directory; import org.apache.lucene.store.RAMDirectory; public class LuceneCustomScoreExample { public static void main(String[] args) throws Exception { // 创建内存索引 Directory indexDirectory = new RAMDirectory(); // 创建索引编写器 IndexWriterConfig config = new IndexWriterConfig(new StandardAnalyzer()); IndexWriter writer = new IndexWriter(indexDirectory, config); // 添加一些文档 Document doc1 = new Document(); doc1.add(new TextField("title", "Lucene in Action", Field.Store.YES)); doc1.add(new TextField("content", "Lucene is a powerful search engine library", Field.Store.YES)); writer.addDocument(doc1); Document doc2 = new Document(); doc2.add(new TextField("title", "Java Concurrency in Practice", Field.Store.YES)); doc2.add(new TextField("content", "Java Concurrency is a great book on Java multi-threading", Field.Store.YES)); writer.addDocument(doc2); // 提交写入器并关闭 writer.commit(); writer.close(); // 搜索并使用自定义评分算法进行排序 IndexSearcher searcher = new IndexSearcher(indexDirectory); Query query = new TermQuery(new Term("content", "search engine")); CustomScoreQuery customScoreQuery = new CustomScoreQuery(query); ScoreDoc[] hits = searcher.search(customScoreQuery, 10).scoreDocs; // 打印结果 System.out.println("Found " + hits.length + " hits."); for (ScoreDoc hit : hits) { Document doc = searcher.doc(hit.doc); System.out.println("Title: " + doc.get("title") + ", Score: " + hit.score); } // 关闭搜索器 searcher.getIndexReader().close(); searcher.close(); } } ``` 这个例子搜索“search engine”并对结果使用自定义评分算法进行排序。在这个例子中,评分算法简单地将子查询得分和值源得分相加。 希望这可以帮助您开始使用自定义评分算法进行Lucene搜索。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值