热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

利用lucene创建实现全站新闻搜索

jar包:lucene-core-2.3.2.jar到相关官网下载建立线程通用类LuceneUtilimportjava.io.File;importjava.io.IOExcep

jar包:lucene-core-2.3.2.jar 到相关官网下载


//建立线程通用类LuceneUtil 

import java.io.File;

import java.io.IOException;

import java.util.ArrayList;

import java.util.List;


import org.apache.lucene.analysis.Analyzer;

import org.apache.lucene.analysis.standard.StandardAnalyzer;

import org.apache.lucene.document.Document;

import org.apache.lucene.document.Field;

import org.apache.lucene.index.IndexWriter;

import org.apache.lucene.queryParser.ParseException;

import org.apache.lucene.queryParser.QueryParser;

import org.apache.lucene.search.Hits;

import org.apache.lucene.search.IndexSearcher;

import org.apache.lucene.search.Query;



public class LuceneUtil implements Runnable{

private List list;

private String path;

public LuceneUtil(List list,String path){

this.list=list;

this.path=path;

}

/**

* 对数据库插叙结果List以及软路径建立索引

* @param list

*/

public void searchBuild() throws Exception {

File indexDir = new File(path);

Analyzer luceneAnalyzer = new StandardAnalyzer();

IndexWriter indexWriter = new IndexWriter(indexDir, luceneAnalyzer, true );

if(list!=null){

for(int i=0;i

Document document =   new  Document();

document.add(new Field("id", String.valueOf(list.get(i).getId()),

                        Field.Store.YES, Field.Index.NO));

document.add(new Field("title", list.get(i).getTitle(), Field.Store.YES,

                        Field.Index.TOKENIZED));

document.add(new Field("content", list.get(i).getContent(), Field.Store.YES,

                       Field.Index.TOKENIZED));

document.add(new Field("updateTime", list.get(i).getPublishTime().toString(), Field.Store.YES,

                        Field.Index.NO));

indexWriter.addDocument(document); 

}

indexWriter.optimize();   

       indexWriter.close();

}

}

    /**

     * 通过传递的内容以及路径地址进行搜索

     * @param search

     * @return

     */

public List searchList(String search,String path)throws IOException, ParseException{

List idList=new ArrayList();

Hits hitsTitle = null ;

Hits hitsCOntent= null ;

IndexSearcher searcher = new  IndexSearcher(path);

Analyzer analyzer = new  StandardAnalyzer();

QueryParser qpTitle = new  QueryParser("title", analyzer);

Query queryTitle = qpTitle.parse(search);

hitsTitle =  searcher.search(queryTitle); 

QueryParser qpCOntent= new  QueryParser("content", analyzer);

Query queryCOntent= qpContent.parse(search);

hitsCOntent= searcher.search(queryContent);

for(int i=0;i

Document doc =  hitsTitle.doc(i);

       String idi=doc.get("id" );

       Integer id=Integer.parseInt(idi);

       idList.add(id);

}

for(int i=0;i

boolean flag=true;

Document doc =  hitsContent.doc(i);

       String idi=doc.get("id" );

       Integer id=Integer.parseInt(idi);

       for(int j=0;j

        Integer idd=(Integer) idList.get(j);

        if(id==idd){

        flag=false;

        }

       }

       if(flag)

       {

       idList.add(id);

       }

}

return idList;

}

/**

* 重写run()方法实现线程建立索引

*/

public void run(){

try {

searchBuild();

} catch (Exception e) {

e.printStackTrace();

}

}

}




//service层方法

/**

* 新闻搜索

* @param search

* @return

* @throws Exception 

*/

public List searchList(String search,String path) throws Exception{

File indexDir = new File(path);

List list=new ArrayList();

List listNews=new ArrayList();

list=newsDao.searchList();

LuceneUtil luceneUtil =new LuceneUtil(list,path);

if(!indexDir.exists())

{

luceneUtil.searchBuild();

}

List listId=luceneUtil.searchList(search,path);

for(int i=0;i

int id=(Integer) listId.get(i);

NewsInfo news=newsDao.findOne(id);

listNews.add(news);

}

return listNews;

}

/**

* 查询已发表的新闻并建立索引

*/

public void buildSearch(String path){

List list=new ArrayList();

list=newsDao.searchList();

LuceneUtil luceneUtil =new LuceneUtil(list,path);

Thread thread=new Thread(luceneUtil);

thread.start();

}



//Controller层分页查询

package com.redwolfsoft.bxzk.controller.news;


import java.util.ArrayList;

import java.util.List;


import javax.servlet.http.HttpServletRequest;


import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;

import org.springframework.ui.Model;

import org.springframework.web.bind.annotation.PathVariable;

import org.springframework.web.bind.annotation.RequestMapping;


@Controller

public class NewsSearch {

@Autowired

private NewsService newsService;

/**

* 搜索新闻

* @param search

* @param currentPageNo

* @return

*/

@RequestMapping(value="/{search}/search/{currentPageNo}/page")

public String searchNews(@PathVariable String search, @PathVariable String currentPageNo,Model model,HttpServletRequest request){

List newsList;

List pageList=new ArrayList();

StringBuffer root = new StringBuffer(request.getSession()

.getServletContext().getRealPath("/"));

root.append("indexFile");

int pageNo=1;

int current=1;

try {

newsList = newsService.searchList(search,root.toString());

int count=newsList.size();

if(count>10){

pageNo=count/10+1;

if(currentPageNo!=null && !"".equals(currentPageNo)){

current=Integer.parseInt(currentPageNo);

if(current<1){

current=1;

}

if(current>pageNo){

current=pageNo;

}

int start=(current-1)*10;

int end=current*10;

if(end>count){

end=count;

}

for(int i=start;i

pageList.add(newsList.get(i));

}

model.addAttribute("searchList", pageList);

}

}else{

model.addAttribute("searchList", newsList);

}

model.addAttribute("search", search);

model.addAttribute("pageNo", pageNo);

model.addAttribute("current", current);

} catch (Exception e) {

e.printStackTrace();

}

return "web/search/search";

}

}



//JSP页面


<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>

<%

String path = request.getContextPath();

String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

%>

<%

int max=(Integer)request.getAttribute("pageNo");

String search=(String)request.getAttribute("search");

int current=(Integer)request.getAttribute("current");

%>

 

   

          

   

 

 

目前位置:首页 - 搜索

 

   

     

       

             

           

           

             

  •            

               

             

  •          

             

             

  •  

             

               

                 

    ${news.title}

                 

    ${news.content}

               

             

  •          

           

             

           

         

 

         <上一页 

          <%for(int z=1;z<=max;z++){ %>

<%=z %>  

 <% }%>

         下一页 >

     

   

   

     

        热门标签

       

          童年阶段

          学生时代

          单身贵族

          踏入社会

          新婚燕尔

          三口之家

          财富传承

          企业团体

          车险攻略

          走进社保

       

     

     

   

 

<%@include file="../common/footer.jsp" %>

 

 


实现效果,第一次搜索的时候进行索引建立,当后台对新闻进行相关操作的时候进行线程更新索引。

本文出自 “只争朝夕” 博客,谢绝转载!

利用lucene创建实现全站新闻搜索,布布扣,bubuko.com


推荐阅读
  • 基于layUI的图片上传前预览功能的2种实现方式
    本文介绍了基于layUI的图片上传前预览功能的两种实现方式:一种是使用blob+FileReader,另一种是使用layUI自带的参数。通过选择文件后点击文件名,在页面中间弹窗内预览图片。其中,layUI自带的参数实现了图片预览功能。该功能依赖于layUI的上传模块,并使用了blob和FileReader来读取本地文件并获取图像的base64编码。点击文件名时会执行See()函数。摘要长度为169字。 ... [详细]
  • HDU 2372 El Dorado(DP)的最长上升子序列长度求解方法
    本文介绍了解决HDU 2372 El Dorado问题的一种动态规划方法,通过循环k的方式求解最长上升子序列的长度。具体实现过程包括初始化dp数组、读取数列、计算最长上升子序列长度等步骤。 ... [详细]
  • 本文讨论了Alink回归预测的不完善问题,指出目前主要针对Python做案例,对其他语言支持不足。同时介绍了pom.xml文件的基本结构和使用方法,以及Maven的相关知识。最后,对Alink回归预测的未来发展提出了期待。 ... [详细]
  • 本文讨论了如何优化解决hdu 1003 java题目的动态规划方法,通过分析加法规则和最大和的性质,提出了一种优化的思路。具体方法是,当从1加到n为负时,即sum(1,n)sum(n,s),可以继续加法计算。同时,还考虑了两种特殊情况:都是负数的情况和有0的情况。最后,通过使用Scanner类来获取输入数据。 ... [详细]
  • 本文介绍了OC学习笔记中的@property和@synthesize,包括属性的定义和合成的使用方法。通过示例代码详细讲解了@property和@synthesize的作用和用法。 ... [详细]
  • Mac OS 升级到11.2.2 Eclipse打不开了,报错Failed to create the Java Virtual Machine
    本文介绍了在Mac OS升级到11.2.2版本后,使用Eclipse打开时出现报错Failed to create the Java Virtual Machine的问题,并提供了解决方法。 ... [详细]
  • 知识图谱——机器大脑中的知识库
    本文介绍了知识图谱在机器大脑中的应用,以及搜索引擎在知识图谱方面的发展。以谷歌知识图谱为例,说明了知识图谱的智能化特点。通过搜索引擎用户可以获取更加智能化的答案,如搜索关键词"Marie Curie",会得到居里夫人的详细信息以及与之相关的历史人物。知识图谱的出现引起了搜索引擎行业的变革,不仅美国的微软必应,中国的百度、搜狗等搜索引擎公司也纷纷推出了自己的知识图谱。 ... [详细]
  • 本文讲述了作者通过点火测试男友的性格和承受能力,以考验婚姻问题。作者故意不安慰男友并再次点火,观察他的反应。这个行为是善意的玩人,旨在了解男友的性格和避免婚姻问题。 ... [详细]
  • 1,关于死锁的理解死锁,我们可以简单的理解为是两个线程同时使用同一资源,两个线程又得不到相应的资源而造成永无相互等待的情况。 2,模拟死锁背景介绍:我们创建一个朋友 ... [详细]
  • 《数据结构》学习笔记3——串匹配算法性能评估
    本文主要讨论串匹配算法的性能评估,包括模式匹配、字符种类数量、算法复杂度等内容。通过借助C++中的头文件和库,可以实现对串的匹配操作。其中蛮力算法的复杂度为O(m*n),通过随机取出长度为m的子串作为模式P,在文本T中进行匹配,统计平均复杂度。对于成功和失败的匹配分别进行测试,分析其平均复杂度。详情请参考相关学习资源。 ... [详细]
  • 动态规划算法的基本步骤及最长递增子序列问题详解
    本文详细介绍了动态规划算法的基本步骤,包括划分阶段、选择状态、决策和状态转移方程,并以最长递增子序列问题为例进行了详细解析。动态规划算法的有效性依赖于问题本身所具有的最优子结构性质和子问题重叠性质。通过将子问题的解保存在一个表中,在以后尽可能多地利用这些子问题的解,从而提高算法的效率。 ... [详细]
  • Java验证码——kaptcha的使用配置及样式
    本文介绍了如何使用kaptcha库来实现Java验证码的配置和样式设置,包括pom.xml的依赖配置和web.xml中servlet的配置。 ... [详细]
  • 高质量SQL书写的30条建议
    本文提供了30条关于优化SQL的建议,包括避免使用select *,使用具体字段,以及使用limit 1等。这些建议是基于实际开发经验总结出来的,旨在帮助读者优化SQL查询。 ... [详细]
  • 本文介绍了lua语言中闭包的特性及其在模式匹配、日期处理、编译和模块化等方面的应用。lua中的闭包是严格遵循词法定界的第一类值,函数可以作为变量自由传递,也可以作为参数传递给其他函数。这些特性使得lua语言具有极大的灵活性,为程序开发带来了便利。 ... [详细]
  • 本文介绍了指针的概念以及在函数调用时使用指针作为参数的情况。指针存放的是变量的地址,通过指针可以修改指针所指的变量的值。然而,如果想要修改指针的指向,就需要使用指针的引用。文章还通过一个简单的示例代码解释了指针的引用的使用方法,并思考了在修改指针的指向后,取指针的输出结果。 ... [详细]
author-avatar
月舞B的啊
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有