`
touchinsert
  • 浏览: 1288907 次
  • 性别: Icon_minigender_1
  • 来自: 北京
文章分类
社区版块
存档分类
最新评论

使用lucene生成html文件索引

阅读更多

我修改了lucene的demo包的IndexHTML类,使其可以被其他Java类调用。

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.Term;
import org.apache.lucene.index.TermEnum;
import java.io.File;
import java.util.Date;
import java.util.Arrays;

//还需调用demo的其他类。
import org.apache.lucene.demo;
/**
* Create html file index for searching
* @author tyrone
*
*/
public class IndexHTML {
private String DocsPath=null;

/**
* the path for index file;
*/
private String IndexFilePath=null;

/**
* true during deletion pass
*/
private boolean deleting = false;
/**
* existing index
*/
private IndexReader reader;
/**
* new index being built
*/
private IndexWriter writer;
/**
* document id iterator
*/
private TermEnum uidIter;


private void indexDocs(File file)throws Exception {
if (file.isDirectory()) { // if a directory
String[] files = file.list(); // list its files
Arrays.sort(files); // sort the files
for (int i = 0; i < files.length; i++) // recursively index them
this.indexDocs(new File(file, files[i]));

} else if (file.getPath().endsWith(".html") || // index .html files
file.getPath().endsWith(".htm") || // index .htm files
file.getPath().endsWith(".txt")) { // index .txt files

if (this.uidIter != null) {
String uid = HTMLDocument.uid(file); // construct uid for doc

while (uidIter.term() != null && uidIter.term().field() == "uid" &&
uidIter.term().text().compareTo(uid) < 0) {
if (deleting) { // delete stale docs
System.out.println("deleting " +
HTMLDocument.uid2url(uidIter.term().text()));
reader.delete(uidIter.term());
}
uidIter.next();
}
if (uidIter.term() != null && uidIter.term().field() == "uid" &&
uidIter.term().text().compareTo(uid) == 0) {
uidIter.next(); // keep matching docs
} else if (!deleting) { // add new docs
Document doc = HTMLDocument.Document(file);
System.out.println("adding " + doc.get("url"));
writer.addDocument(doc);
}
} else { // creating a new index
Document doc = HTMLDocument.Document(file);
System.out.println("adding " + doc.get("url"));
writer.addDocument(doc); // add docs unconditionally
}
}
return;
}

/**
* Walk directory hierarchy in uid order, while keeping uid iterator from
* existing index in sync. Mismatches indicate one of:
* (a) old documents to be deleted;
* (b) unchanged documents, to be left alone;
* or (c) new documents, to be indexed.
*/

private void indexDocs(File file, String index, boolean create)
throws Exception {
if (!create) { // incrementally update

reader = IndexReader.open(index); // open existing index
uidIter = reader.terms(new Term("uid", "")); // init uid iterator

this.indexDocs(file);

if (deleting) { // delete rest of stale docs
while (uidIter.term() != null && uidIter.term().field() == "uid") {
System.out.println("deleting " +
HTMLDocument.uid2url(uidIter.term().text()));
reader.delete(uidIter.term());
uidIter.next();
}
deleting = false;
}

uidIter.close(); // close uid iterator
reader.close(); // close existing index

} else // don't have exisiting
this.indexDocs(file);

}
/**
* if create=true, create a new index, else refresh old index.
* @param create
*/
public void run(boolean create) {
try {
String index = "index";
File root = null;
if (this.IndexFilePath!=null) { // index file path
index = this.IndexFilePath;
}
if (this.DocsPath==null){
System.out.println("root directory is not set");
return;
}
root = new File(this.DocsPath);
Date start = new Date();
/**
* not create then maintenance
*/
if (!create) { // delete stale docs
this.deleting = true;
this.indexDocs(root, index, create);
}

writer = new IndexWriter(index, new StandardAnalyzer(), create);
writer.maxFieldLength = 1000000;

this.indexDocs(root, index, create); // add new docs

System.out.println("Optimizing index...");
writer.optimize();
writer.close();

Date end = new Date();

System.out.print(end.getTime() - start.getTime());
System.out.println(" total milliseconds");
} catch (Exception e) {
System.out.println(" caught a " + e.getClass() +
"\n with message: " + e.getMessage());
}
return;
}

/**
* @return Returns the IndexFilePath.
*/
public String getIndexFilePath() {
return IndexFilePath;
}
/**
* @param IndexFilePath The IndexFilePath to set.
*/
public void setIndexFilePath(String property1) {
this.IndexFilePath = property1;
}
/**
* @return Returns the DocsPath.
*/
public String getDocsPath() {
return DocsPath;
}
/**
* @param DocsPath The DocsPath to set.
*/
public void setDocsPath(String property1) {
this.DocsPath = property1;
}

/**
* test
* @param args
*/
public static void main(String[] args){
IndexHTML ih=new IndexHTML();
ih.setDocsPath("D:\\MyProject\\colimas\\clms-doc2\\html");
ih.setIndexFilePath("D:\\MyProject\\colimas\\index");
ih.run(true);
}
}

运行后生成3个文件_3i8.cfs,deletable,segments

搜索文件类:

/*
* Created on 2005/07/28
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package com.nova.colimas.search.query;

/**
* @author tyrone
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class HitsHTMLDoc {

private String Title;

private String Path;

private String Url;

/**
* @return Returns the Url.
*/
public String getUrl() {
return Url;
}
/**
* @param Url The Url to set.
*/
public void setUrl(String property1) {
this.Url = property1;
}
/**
* @return Returns the Path.
*/
public String getPath() {
return Path;
}
/**
* @param Path The Path to set.
*/
public void setPath(String property1) {
this.Path = property1;
}
/**
* @return Returns the Title.
*/
public String getTitle() {
return Title;
}
/**
* @param Title The Title to set.
*/
public void setTitle(String property1) {
this.Title = property1;
}
}

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.search.Searcher;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.Hits;
import org.apache.lucene.queryParser.QueryParser;
/**
* @author tyrone
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class SearchFiles {

private Hits hits;

public Hits getHits(){
return hits;
}

public HitsHTMLDoc[] run(String indexFilePath,String line){
HitsHTMLDoc[] hitdocs;
try {
Searcher searcher = new IndexSearcher(indexFilePath);
Analyzer analyzer = new StandardAnalyzer();
Query query = QueryParser.parse(line, "contents", analyzer);
System.out.println("Searching for: " + query.toString("contents"));
this.hits = searcher.search(query);
if (this.hits.length()==0) return null;
System.out.println(this.hits.length() + " total matching documents");
hitdocs=new HitsHTMLDoc[this.hits.length()];
for (int i = 0; i < hits.length(); i++) {
Document doc = this.hits.doc(i);
String path = doc.get("path");
if (path != null) {
hitdocs[i].setPath(path);
} else {
String url=doc.get("url");
if (url != null) {
hitdocs[i]=new HitsHTMLDoc();
hitdocs[i].setUrl(url);
String title=doc.get("title");
if (title!=null)
hitdocs[i].setTitle(title);
} else {
System.out.println(i + ". " + "No path nor URL for this document");
}
}

}
searcher.close();
return hitdocs;
}catch(Exception e){
System.out.println(" caught a " + e.getClass() +
"\n with message: " + e.getMessage());
}
return null;
}
/**
* test
* args=queries
* @author tyrone
*
*/
public static void main(String[] args){
SearchFiles se=new SearchFiles();
String query="";
HitsHTMLDoc[] hitsdoc;
for (int i=0;i<args.length;i++)
query=query+args[i]+" ";
hitsdoc=se.run("D:\\MyProject\\colimas\\index",query);
if (hitsdoc==null){
System.out.println("nothing");
return;
}
for (int l=0;l<hitsdoc.length;l++){
System.out.println("url:"+hitsdoc[l].getUrl());
System.out.println("path:"+hitsdoc[l].getPath());
System.out.println("title:"+hitsdoc[l].getTitle());
}
}

}

注意事项:

1 引用lucene debug你的应用程序时虽然不需要下面的jar包,但每次会提示URLClassPath.class异常,为方便起见还是下载这些jar包。
relaxngDatatype.jar
commons-beanutils.jar
commons-collections.jar
commons-digester.jar
commons-logging.jar
commons-validator.jar
jakarta-oro.jar
struts-legacy.jar

2 生成index文件的目录里不能有其他目录,如果有则会试图删除或报错

分享到:
评论

相关推荐

    lucene索引非txt文档笔记

    lucene 是全开源文索引搜索引擎,使用它可以很快的架设我们自己的搜索引擎,但遗憾的是它默认只对txt和html格式文档生成index,但我们常常要使用其他的文档如word,pdf等,我搜集了这几种文档生成index的笔记

    luxugang#Lucene-7.5.0#索引文件的读取(四)-html1

    在文章索引文件的生成(十一)之dim&&dii中我们知道,父节点提供的minPackedValue和maxPackedValue对应的数值范围实际是大于或等于叶

    基于lucene的搜索引擎总结

    不允许使用多个IndexWriter或IndexReader实例同时对一个索引进行修改 IndexWriter和IndexReader是线程安全的,可以被多线程共享 全文索引/搜索 中文分词器 最大匹配法(机械分词):按照一定的策略将待分析的汉字串...

    lean:Lucene文本分析工具

    DocIndexer应用程序以各种格式和编码提取文档,使用用户可配置的Lucene分析器对其进行分析,并生成Lucene反向索引。 LuceneToMtx应用程序读取索引,对术语进行可选过滤,并生成具有匹配字典和文档文件的术语频率...

    solr 企业搜索引擎教程

    某些情况下可能需要进行编码,Solr 可以阅读和使用构建到其他 Lucene 应用程序中的索引。此 外,很多 Lucene 工具(如 Nutch、 Luke)也可以使用 Solr 创建的索引 Solr 的特性包括:  高级的全文搜索功能  专为高通量...

    MF00114-JAVASSF项目框架源码.zip

    JAVA SSF项目框架源码 后台管理系统源码 注意:不带技术支持,有帮助文件,虚拟商品,发货不退,看好再拍。...Ehcache (作为二级缓存,提高性能)、Lucene 和Quartz (定时生成索引)、Log4j(记录日志)等等。

    web开发常用jar

    通过iText不仅可以生成PDF或rtf的文档,而且可以将XML、Html文件转化为PDF文件。 iTextAsian.jar itext中关于亚洲编码的类库,在这里用于中文字体的输入。 junit.jar Junit包,当你运行Hibernate自带的测试...

    JAVA上百实例源码以及开源项目

     Java实现HTTP连接与浏览,Java源码下载,输入html文件地址或网址,显示页面和HTML源文件,一步步的实现过程请下载本实例的Java源码,代码中包括丰富的注释,对学习有帮助。 Java实现的FTP连接与数据浏览程序 1个...

    JAVA上百实例源码以及开源项目源代码

     Java实现HTTP连接与浏览,Java源码下载,输入html文件地址或网址,显示页面和HTML源文件,一步步的实现过程请下载本实例的Java源码,代码中包括丰富的注释,对学习有帮助。 Java实现的FTP连接与数据浏览程序 1个...

    java开发常用jar包

    通过iText不仅可以生成PDF或rtf的文档,而且可以将XML、Html文件转化为PDF文件。 iTextAsian.jar itext中关于亚洲编码的类库,在这里用于中文字体的输入。 junit.jar Junit包,当你运行Hibernate自带的测试代码的...

    一个简单的java爬虫产品

    最近一直在研究爬虫和Lucene,虽然开始决定选用Heritrix来执行爬虫操作,但是后来发现用它来做还是存在一定的问题,比如需要程序生成相应的XML文件,对于同一个Job,怎样才能保证重复运行该Job时文件夹始终是同一个...

    基于SSM实现的招聘考试系统.zip

    试题爬取通过WebCollector爬虫框架网上爬取试题,通过Lucene全文搜索试题,通过遗传算法生成试卷 爬虫(Web Crawler)是一种自动化程序,用于从互联网上收集信息。其主要功能是访问网页、提取数据并存储,以便后续...

    java开源包8

    JCaptcha4Struts2 是一个 Struts2的插件,用来增加验证码的支持,使用时只需要用一个 JSP 标签 (&lt;jcaptcha:image label="Type the text "/&gt; ) 即可,直接在 struts.xml 中进行配置,使用强大的 JCaptcha来生成验证码...

    java开源包1

    JCaptcha4Struts2 是一个 Struts2的插件,用来增加验证码的支持,使用时只需要用一个 JSP 标签 (&lt;jcaptcha:image label="Type the text "/&gt; ) 即可,直接在 struts.xml 中进行配置,使用强大的 JCaptcha来生成验证码...

    java开源包11

    JCaptcha4Struts2 是一个 Struts2的插件,用来增加验证码的支持,使用时只需要用一个 JSP 标签 (&lt;jcaptcha:image label="Type the text "/&gt; ) 即可,直接在 struts.xml 中进行配置,使用强大的 JCaptcha来生成验证码...

    java开源包2

    JCaptcha4Struts2 是一个 Struts2的插件,用来增加验证码的支持,使用时只需要用一个 JSP 标签 (&lt;jcaptcha:image label="Type the text "/&gt; ) 即可,直接在 struts.xml 中进行配置,使用强大的 JCaptcha来生成验证码...

    java开源包3

    JCaptcha4Struts2 是一个 Struts2的插件,用来增加验证码的支持,使用时只需要用一个 JSP 标签 (&lt;jcaptcha:image label="Type the text "/&gt; ) 即可,直接在 struts.xml 中进行配置,使用强大的 JCaptcha来生成验证码...

    java开源包6

    JCaptcha4Struts2 是一个 Struts2的插件,用来增加验证码的支持,使用时只需要用一个 JSP 标签 (&lt;jcaptcha:image label="Type the text "/&gt; ) 即可,直接在 struts.xml 中进行配置,使用强大的 JCaptcha来生成验证码...

    java开源包5

    JCaptcha4Struts2 是一个 Struts2的插件,用来增加验证码的支持,使用时只需要用一个 JSP 标签 (&lt;jcaptcha:image label="Type the text "/&gt; ) 即可,直接在 struts.xml 中进行配置,使用强大的 JCaptcha来生成验证码...

Global site tag (gtag.js) - Google Analytics