lucene5.0教程 检索把论坛用户全抓空 怎么做到

Lucene给文本索引和搜索功能的应用_Linux编程_Linux公社-Linux系统门户网站
你好,游客
Lucene给文本索引和搜索功能的应用
来源:Linux社区&
作者:Spring_java_gg
最近一段时间由于公司需要 ,模糊搜索出相似的关键词,所以直接考虑使用了Lucene。
Lucene允许你往程序中添加搜索功能,Lucene能够把你从文本中解析出来的数据进行索引和搜索 ,Lucene不关心数据来源 甚至不关心语种,不过你需要把它转换成文本格式。也就是说你可以搜索 html网页,文本文档,word文档 ,pdf,或者其他一些 总之 只要能够提取出文本信息的即可。同样你也可以利用Lucene来索引存储在数据库中的数据,以给你的用户提供一些& 比如 全文搜索功能等 ,反正Lucene的功能很是强大。里面还有很多开源的对不同语言进行分析的插件等。
下面我介绍一个例子 ,这里我进行对 一个txt文档的 每一行进行了 索引的添加 ,也就是说& 把每一行 当作一个document对象来处理,实际上在Lucene中 每一个document 相当于我们在数据库中的库名, 而每个field相当于我们的表名 ,它能够对文本进行自动处理去掉里面的一些语气词,它能把你规定的域当作关键词来进行索引 以备查询时使用,Lucene比较容易使用 ,但是不如数据库灵活,速度很快。下面 我用一个例子来说明(这里我用的Lucene4.7.2,最高版本 ,你需要注意把需要的一些jar包引入的到你的工程中,使用maven可直接引入依赖/artifact/org.apache.Lucene需要的全部引入)我这里写了一个实例 你可以进行参考学习使用方法。
--------------------------------------分割线 --------------------------------------
基于Lucene多索引进行索引和搜索 http://
Lucene 实战(第2版) 中文版 配套源代码
Lucene 实战(第2版) PDF高清中文版
使用Lucene-Spatial实现集成地理位置的全文检索
分布式搜索运行框架 Nut 1.0a9
Lucene + Hadoop 分布式搜索运行框架 Nut 1.0a8
Lucene + Hadoop 分布式搜索运行框架 Nut 1.0a7
Project 2-1: 配置Lucene, 建立WEB查询系统[ 10.10]
--------------------------------------分割线 --------------------------------------
package lucene.home.
/**&* @author chenlongquan&* Copyright Manning Publications Co..com&*&* Licensed under the Apache License, Version 2.0 (the "License");&* you may not use this file except in compliance with the License.&* You may obtain a copy of the License at&*&*& &
&* Unless required by applicable law or agreed to in writing, software&* distributed under the License is distributed on an "AS IS" BASIS,&* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.&* See the License for the specific lan& & & */
//创建索引import org.apache.lucene.index.IndexWimport org.apache.lucene.index.IndexWriterCimport org.apache.lucene.analysis.Aimport org.apache..smart.SmartChineseAimport org.apache.lucene.analysis.standard.StandardAimport org.apache.lucene.document.Dimport org.apache.lucene.document.Fimport org.apache.lucene.document.TextFimport org.apache.lucene.store.FSDimport org.apache.lucene.store.Dimport org.apache.lucene.util.Vimport java.io.BufferedRimport java.io.Fimport java.io.FileFimport java.io.FileInputSimport java.io.IOEimport java.io.FileRimport java.io.InputStreamRimport java.io.LineNumberRimport java.util.ArrayLimport java.util.HashSimport java.util.Limport java.util.S/**&* This code was originally build for the index&* &*/public class Indexer {
& public static void main(String[] args) throws Exception {& & & & String indexDir = "f:\\index";& & & &
//1& & String dataDir = "f:\\baidu";& & & & & //2
& & long start = System.currentTimeMillis();& & Indexer indexer = new Indexer(indexDir);& & int numI& & try {& & & numIndexed = indexer.index(dataDir, new TextFilesFilter());& & } finally {& & & indexer.close();& & }& & long end = System.currentTimeMillis();
& & System.out.println("Indexing " + numIndexed + " files took "& & & + (end - start) + " milliseconds");& }&
private IndexW& public Indexer(String indexDir) throws IOException {& & & Directory dir = FSDirectory.open(new File(indexDir));& & & writer = new IndexWriter(dir,indexWriterConfig());& & & //在这里进行索引的调试& & & & & &
& public void close() throws IOException {& & writer.close();& & & & & & & & & & & & & &
//4& }& private IndexWriterConfig indexWriterConfig(){&Analyzer analyzer = new SmartChineseAnalyzer(Version.LUCENE_47);&IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_47, analyzer);&}& public int index(String dataDir, FileFilter filter)& & throws Exception {
& & File[] files = new File(dataDir).listFiles();
& & for (File f: files) {& & & if (!f.isDirectory() &&& & & & & !f.isHidden() &&& & & & & f.exists() &&& & & & & f.canRead() &&& & & & & (filter == null || filter.accept(f))) {& & & & indexFile(f);& & & }& & }
& & return writer.numDocs();& & & & & & & & & &
& private static class TextFilesFilter implements FileFilter {& & public boolean accept(File path) {& & & return path.getName().toLowerCase()& & & & //6& & & & & &
.endsWith(".txt");& & & & & & & & & //6& & }& }&
/**& & * 遍历每一个文件,然后读出文件中的每一行数据,当成一个document来处理 & & * @param f& & * @throws Exception& & */& private void indexFile(File f) throws Exception {& & System.out.println("Indexing " + f.getCanonicalPath());&
// Document doc = getDocument(f);& & List&String& lists = readFileNoDup(f);& & for(String list:lists){& & Document doc = new Document();& & doc.add(new Field("contents",list,TextField.TYPE_STORED));& & writer.addDocument(doc);& &
& & }& & & & & & & & & & & & & & & & //10& }& //读取一个文件& private List&String& readFile(File filePathAndName)throws IOException {
FileInputStream fis = new FileInputStream(filePathAndName);InputStreamReader isr = new InputStreamReader(fis, "UTF-8");BufferedReader br = new BufferedReader(isr);LineNumberReader lnr = new LineNumberReader(br);
List&String& returnValue = new ArrayList&String&();int cnt = 0;while (true) {cnt++;String tempStr = lnr.readLine();if (tempStr == null)if (tempStr.length() & 2)returnValue.add(tempStr);}lnr.close();br.close();isr.close();fis.close();return returnV}& //读取一个文件并排重后返回& public static List&String& readFileNoDup(File filePathAndName)throws IOException {&FileInputStream fis = new FileInputStream(filePathAndName);InputStreamReader isr = new InputStreamReader(fis, "UTF-8");BufferedReader br = new BufferedReader(isr);LineNumberReader lnr = new LineNumberReader(br);
Set&String& set = new HashSet&String&();while (true) {String tempStr = lnr.readLine();if (tempStr == null)if (tempStr.length() & 2)set.add(tempStr.trim());}lnr.close();br.close();isr.close();fis.close();List&String& returnValue = new ArrayList&String&(set.size());returnValue.addAll(set);return returnV& & & & }}
//对刚才已经建好的索引进行搜索
package lucene.home.
/**&* Copyright Manning Publications Co.&*&* Licensed under the Apache License, Version 2.0 (the "License");&* you may not use this file except in compliance with the License.&* You may obtain a copy of the License at&*&*& &
&*&* Unless required by applicable law or agreed to in writing, software&* distributed under the License is distributed on an "AS IS" BASIS,&* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.&* See the License for the specific lan& & & */
import java.io.Fimport java.io.IOEimport java.util.ArrayLimport java.util.L
import org.apache..smart.SmartChineseAimport org.apache.lucene.document.Dimport org.apache.lucene.index.DirectoryRimport org.apache.lucene.index.IndexRimport org.apache.lucene.queryparser.classic.ParseEimport org.apache.lucene.queryparser.classic.QueryPimport org.apache.lucene.search.IndexSimport org.apache.lucene.search.Qimport org.apache.lucene.search.ScoreDimport org.apache.lucene.search.Simport org.apache.lucene.search.SortFimport org.apache.lucene.search.TopDimport org.apache.lucene.search.TopFieldCimport org.apache.lucene.search.TopFieldDimport org.apache.lucene.store.FSDimport org.apache.lucene.store.SimpleFSDimport org.apache.lucene.util.V
// From chapter 1
/**&* This code was originally written for& searcher&* &*/public class Searcher {
& public static void main(String[] args) throws IllegalArgumentException,& & & & IOException, ParseException {& & & & & & & & & &
& & final String indexDir = "e:\\soso\\soso";& & & &
String q = " ";//输入你添加的所以 进行模糊搜索 & & docs = query(indexDir, q)& &
& public static void search(String indexDir, String q)& & throws IOException, ParseException {&IndexReader reader = DirectoryReader.open(FSDirectory.open(new File(indexDir)));&
// Directory dir = FSDirectory.open(new File(indexDir)); //3& & IndexSearcher is = new IndexSearcher(reader);&
& & QueryParser parser = new QueryParser(Version.LUCENE_47,"contents",new SmartChineseAnalyzer(Version.LUCENE_47));& & & & & & Query query = parser.parse(q);& & & & & & & //4&
& & long start = System.currentTimeMillis();& & TopDocs hits = is.search(query, 500); //5&
& & //ScoreDoc[] hits = is.search(query, null, 10).scoreD& & long end = System.currentTimeMillis();
& & System.err.println("Found " + hits.totalHits +&
//6& & & & " document(s) (in " + (end - start) +& & & & // 6& & & " milliseconds) that matched query '" +& &
// 6& & & q + "':");& & & & & & & & & & & & & & & & &
& & for(ScoreDoc scoreDoc : hits.scoreDocs) {& & & Document doc = is.doc(scoreDoc.doc);& & & & & & &
//7& & & & & & System.out.println(doc.get("contents"));& & }& & reader.close();& }&
& & private static List&String& query(String indexDir, String searcher) throws IOException, ParseException{& & & & if (searcher == null || searcher.length() == -1) {& & & & & && & & & & }& & & & & &
searcher = searcher.trim();& & & & & if (searcher.length() == 0) {& & & & & && & & & & }& & & & & & & IndexReader reader = DirectoryReader.open(FSDirectory.open(new File(indexDir)));//open the index& & //IndexReader reader = DirectoryReader.open(SimpleFSDirectory.open(new File(indexDir)));//open the index& & IndexSearcher is = new IndexSearcher(reader);//find the content& & QueryParser parser = new QueryParser(Version.LUCENE_47, "contents", new SmartChineseAnalyzer(Version.LUCENE_47));//parser the content& & Query query = parser.parse(searcher);& & TopFieldDocs hits = is.search(query, 100, new Sort(new SortField("contents", SortField.Type.SCORE, false)));& & TopDocs hits1 = is.search(query, 200);//搜索出前200条数据& 按照评分进行排序& & List&String& list = new ArrayList&String&();& & for(ScoreDoc scoreDoc : hits.scoreDocs){& & Document doc = is.doc(scoreDoc.doc);& & list.add(doc.get("contents"));& & }& & reader.close();& && & }}
//这里我主要给文档中的文本进行添加了索引 ,你也可以在Field 中给路径 等等一些属性进行添加索引&
具体你可以搜索lucene api&进行使用 里面的一些方法。我这里说的比较粗,有问题欢迎讨论。
Lucene 的详细介绍:Lucene 的下载地址:
本文永久更新链接地址:
相关资讯 & & &
& (03月20日)
& (03月06日)
& (03月20日)
& (03月20日)
& (03月06日)
图片资讯 & & &
   同意评论声明
   发表
尊重网上道德,遵守中华人民共和国的各项有关法律法规
承担一切因您的行为而直接或间接导致的民事或刑事法律责任
本站管理人员有权保留或删除其管辖留言中的任意内容
本站有权在网站内转载或引用您的评论
参与本评论即表明您已经阅读并接受上述条款初学者如何做出一个搜索网站 lucene_百度知道
初学者如何做出一个搜索网站 lucene
最好有视频的
提问者采纳
看lucene demo
提问者评价
其他类似问题
lucene的相关知识
按默认排序
其他1条回答
多看多学啊!
等待您来回答
下载知道APP
随时随地咨询
出门在外也不愁当前访客身份:游客 [
当前位置:
发布于 日 10时,
一个网站内部的lucene检索,通过输入要检索的网址和检索内容进行检索。一次小练习,还有诸多后续扩充,例如各种不同的检索方式的加入,可以借鉴检索练习。和大家分享下,一起提高,望指点
代码片段(2)
MySearch.java&~&10KB&&&&
package myE
* @author: cuiH
* Date: 13-7-9
* 作用和目的:一个简单的搜索引擎,可以在一个网站内指定区域的关键词的搜索
* 本程序:通过对学校网站的所有题目中进行检索“张德江”
* 检索结果:共有标题122个,符合的结果古河标准的有12个
import org.apache.lucene.analysis.A
import org.apache.lucene.document.D
import org.apache.lucene.document.F
import org.apache.lucene.index.CorruptIndexE
import org.apache.lucene.index.IndexR
import org.apache.lucene.index.IndexW
import org.apache.lucene.index.IndexWriterC
import org.apache.lucene.queryParser.ParseE
import org.apache.lucene.queryParser.QueryP
import org.apache.lucene.search.IndexS
import org.apache.lucene.search.Q
import org.apache.lucene.search.ScoreD
import org.apache.lucene.search.TopScoreDocC
import org.apache.lucene.store.D
import org.apache.lucene.store.FSD
import org.apache.lucene.util.V
import org.htmlparser.NodeF
import org.htmlparser.P
import org.htmlparser.beans.StringB
import org.htmlparser.filters.NodeClassF
import org.htmlparser.tags.LinkT
import org.htmlparser.util.NodeL
import org.htmlparser.util.ParserE
import org.htmlparser.visitors.HtmlP
import org.wltea.analyzer.lucene.IKA
import java.io.F
import java.io.IOE
import java.util.ArrayL
import java.util.L
public class MySearch {
//索引目录
private static final String INDEX_DIR = "D:/lucene/index";
//已经存在的url列表
private static List&String& urls = new ArrayList&String&();
* 索引器,对目标url创建索引
* @param url 目标网址
* @throws java.io.IOException
* @throws org.htmlparser.util.ParserException
private static void indexer(String url) throws IOException, ParserException {
//存储索引的目录
File indexDir = new File(INDEX_DIR);
//目录不存在,创建该目录
if (!indexDir.exists()) {
indexDir.mkdir();
//获取网页纯文本
String content = getText(url);
//获取网页标题
String title = getTitle(url);
System.out.println("title:" + title);
if (title == null || content == null || content.trim().equals("")) {
System.out.println("content:" + content);
URL path=new URL(url);
InputStream stream=path.openStream();
Reader reader=new InputStreamReader(stream);
Reader reader=new InputStreamReader(new ByteArrayInputStream(content.getBytes()));
Reader reader2=new InputStreamReader(new ByteArrayInputStream(title.getBytes()));
Document doc = new Document();
//加入url域
doc.add(new Field("url", url, Field.Store.YES,
Field.Index.NOT_ANALYZED));
//加入标题域
doc.add(new Field("title", title, Field.Store.YES,
Field.Index.ANALYZED));
doc.add(new Field("title",reader2));
//Index.ANALYZED分词后构建索引
//加入内容域
doc.add(new Field("content", content, Field.Store.YES,
Field.Index.ANALYZED));
doc.add(new Field("content",reader));
//创建IKAnalyzer中文分词对象
Analyzer analyzer = new IKAnalyzer();
//索引目录
Directory dir = FSDirectory.open(indexDir);
//配置IndexWriterConfig
IndexWriterConfig iwConfig = new IndexWriterConfig(Version.LUCENE_36, analyzer);
iwConfig.setOpenMode(IndexWriterConfig.OpenMode.CREATE_OR_APPEND);
//创建写索引对象
IndexWriter writer = new IndexWriter(dir, iwConfig);
//写入文档
writer.addDocument(doc);
writer.close();
//创建了索引的网址加入到已经存在的网址列表中
urls.add(url);
* 搜索器,根据输入的文本去搜索
* @param words 输入的文本
* @param field 搜索的域
* @throws org.apache.lucene.index.CorruptIndexException
* @throws IOException
* @throws org.apache.lucene.queryParser.ParseException
@SuppressWarnings("deprecation")
private static void searcher(String words, String field) throws CorruptIndexException,
IOException, ParseException {
File indexDir = new File(INDEX_DIR);
//索引目录
Directory dir = FSDirectory.open(indexDir);
//根据索引目录创建读索引对象
IndexReader reader = IndexReader.open(dir);
//搜索对象创建
IndexSearcher searcher = new IndexSearcher(reader);
//IKAnalyzer中文分词
Analyzer analyzer = new IKAnalyzer();
//创建查询解析对象
QueryParser parser = new QueryParser(Version.LUCENE_36, field, analyzer);
parser.setDefaultOperator(QueryParser.AND_OPERATOR);
//根据域和目标搜索文本创建查询器
Query query = parser.parse(words);
System.out.println("Searching for: " + query.toString(field));
//对结果进行相似度打分排序
TopScoreDocCollector collector = TopScoreDocCollector.create(5 * 10, false);
searcher.search(query, collector);
//获取结果
ScoreDoc[] hits = collector.topDocs().scoreD
int numTotalHits = collector.getTotalHits();
System.out.println(numTotalHits + " total matching pages");
//显示搜索结果
for (int i = 0; i & hits. i++) {
Document doc = searcher.doc(hits[i].doc);
String url = doc.get("url");
String title = doc.get("title");
String content = doc.get("content");
System.out.println((i + 1) + "." + title);
System.out.println("-----------------------------------");
System.out.println(content.substring(0, 100) + "......");
System.out.println("-----------------------------------");
System.out.println(url);
System.out.println();
* 收入网站
* @param url 网站首页url,也可以为网站地图url
* @throws ParserException
* @throws IOException
* @throws ParseException
private static void addSite(String url) throws ParserException, IOException, ParseException {
long start = System.currentTimeMillis();
System.out.println("start add...");
//获取目标网页的所有链接
List&String& links = getLinks(url);
System.out.println("url count:" + links.size());
for (int i = 0; i & links.size(); i++) {
String link = links.get(i);
System.out.println((i + 1) + "." + link);
if (!urls.contains(link)) {
//对未创建过索引的网页创建索引
indexer(link);
System.out.println("[" + link + "] exist");
System.out.println("end...");
long end = System.currentTimeMillis();
System.out.println("cost " + (end - start) / 1000 + " seconds");
* 获取网页纯文本
* @param url 目标网址
* @throws ParserException
private static String getText(String url) throws ParserException {
StringBean sb = new StringBean();
// 设置不需要得到页面所包含的链接信息
sb.setLinks(false);
// 设置将不间断空格由正规空格所替代
sb.setReplaceNonBreakingSpaces(true);
// 设置将一序列空格由一个单一空格所代替
sb.setCollapse(true);
// 传入要解析的URL
sb.setURL(url);
// 返回解析后的网页纯文本信息
String content = sb.getStrings();
// System.out.println(content);
* 获取网页标题
* @param path
* @throws IOException
* @throws ParserException
private static String getTitle(String path) throws IOException,
ParserException {
String title = "";
Parser parser = new Parser(path);
HtmlPage page = new HtmlPage(parser);
parser.visitAllNodesWith(page);
title = page.getTitle();
} catch (Exception e) {
//e.printStackTrace();
title = "no title";
return title.trim();
* 获取网页中所有的链接
* @param url
* @throws org.htmlparser.util.ParserException
private static List&String& getLinks(String url) throws ParserException {
List&String& links = new ArrayList&String&();
//创建链接节点的过滤器
NodeFilter filter = new NodeClassFilter(LinkTag.class);
Parser parser = new Parser();
parser.setURL(url);
//设置目标网页的编码方式
parser.setEncoding("gb2312");
//因为有些时候不清楚目标网页的编码方式,这里我们采用指定一
//个编码集合,然后通过试探的方式得到目标网页的编码方式
NodeList list = parser.extractAllNodesThatMatch(filter);
for (int i = 0; i & list.size(); i++) {
LinkTag node = (LinkTag) list.elementAt(i);
//获取链接的目标网址
String link = node.extractLink();
if (link != null && !link.trim().equals("") && !link.equals("#")) {
//将目标网址加入到该页面的所有网址列表中
links.add(link);
public static void main(String[] args) throws IOException, ParseException,
InterruptedException, ParserException {
String url = "http://www./";
//收录网站
addSite(url);
//搜有标题带有“搜索引擎”字眼的网页
searcher("张德江", "title");
2.&[图片] 运行结果.jpg&&&&
开源中国-程序员在线工具:
相关的代码(35)
27回/8197阅
35回/7609阅
16回/6698阅
10回/5082阅
44回/3604阅
4回/3715阅
8回/3595阅
5回/3595阅
2回/3379阅
1回/3133阅
楼主可以上传可以跑的工程,我们还要找包啊?
2楼:lvwenwen 发表于
跑下你的列子,找包都要找一个小时,操蛋
3楼:崔小涣 发表于
引用来自“lvwenwen”的评论跑下你的列子,找包都要找一个小时,操蛋我也新手 ,不知道怎么上传jar包
4楼:lvwenwen 发表于
打包,压缩上传
5楼:徐福周 发表于
有jar包吗 给个
开源从代码分享开始
崔小涣的其他代码基于s2sh +mysql的 lucene大型网站的站内搜索实现 - 峰萧易水
- 博客频道 - CSDN.NET
1319人阅读
前一段时间 公司在搞数据的垂直搜索 ,自己也学了点一些网络爬虫的知识 与 索引建立的知识 ,并且 自己一直是 csdn的网站爱好者 ,平常找资料 通常就是通过 csdn的站内搜索 ,所以自己那天也写了个简单的站内搜索 ,当然不能与csdn比 我的只是自己爱好玩玩 不是很专业 上面是截图
1. 因为网站数据量庞大的时候 肯定不能再像 我们查数据那样 ,所以我们要对庞大的数据进行索引 这是lucene是一个不错的工具 ,因为本身是Java写的 所以不是很难 。
&&下面是 源码 如果需要学习者可以去下载 写的不好的地方 大家原谅 .
数据库用的是 mysql 大家 可以根据 hibernate来建立数据库表 比较简单的一张表
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:18555次
排名:千里之外
原创:11篇
评论:35条
(3)(1)(2)(2)(1)(1)(1)(1)

我要回帖

更多关于 lucene 的文章

 

随机推荐