`
touchinsert
  • 浏览: 1316286 次
  • 性别: 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 3.6 检索文件 pdf word ppt excel txt html xml

    要开始使用Lucene进行文件检索,你需要指定两个关键目录:检索目录和索引目录。检索目录包含了需要被搜索的文件,而索引目录则用于存储生成的索引文件。通过调用提供的静态方法,可以快速完成索引的创建。这个过程...

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

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

    lucene学习lucene学习

    2. 创建索引:清单 1 展示了一个简单的 Java 示例,演示如何使用 Lucene 对一个目录中的 .txt 文件创建索引。在这个例子中,`fileDir` 指定包含待索引文本文件的目录,`indexDir` 是存储 Lucene 索引文件的位置。`...

    Lucene 3.0.1 全文检索引擎的架构 对文件,数据库建索引,及查询(高亮显示)

    - "工具"可能指的是使用Lucene时可能需要的辅助库,比如这里提到的`pdfbox-1.1.0.jar`用于PDF文件处理,`jxl.jar`可能用于读取Excel文件,而`word-extractors-0.4.jar`可能是用于处理不同文件格式的文本提取工具。...

    基于Lucene的Lucene

    3. **索引文件**: 使用IndexWriter的addDocument方法将Document添加到索引中。这个过程会调用Analyzer处理文本,并创建倒排索引。 4. **查询处理**: 用户输入查询后,使用QueryParser解析查询字符串,生成Query对象...

    Lucene3.0增删改查和关键字高亮实例

    首先,为每个匹配的片段生成一个`ScoredFragment`,然后使用高亮策略(如HTML标签包围)将这些片段插入原始文本中。 项目中的`ZZUluceneTest1`很可能是主测试类,包含了上述所有操作的示例代码。通过阅读和运行这些...

    用lucene实现摘要的高亮点

    在IT领域,Lucene是一个广泛使用的全文搜索引擎库,它提供了高效、灵活的索引和搜索功能。本篇文章主要探讨如何利用Lucene实现文件摘要的自动提取,并进行关键词高亮显示。这一过程涉及到Lucene的Highlighter组件,...

    实现多种文件格式的Lucene全文搜索功能的dom实例

    5. **查询处理**:用户输入查询后,Lucene会分析查询字符串并生成查询对象。查询对象与索引进行匹配,返回匹配的文档列表。 6. **高亮显示**:搜索结果中,关键词需要高亮显示。Lucene提供Highlighter组件,它可以...

    lucene_heritrix 搜索引擎

    它与Lucene和Heritrix的关系可能在于,FMPP可以用来自动化生成配置文件或者索引展示页面,这样在构建搜索引擎时可以提高效率和一致性。 总结一下,Lucene和Heritrix是构建搜索引擎的关键组件。Lucene负责高效地索引...

    Lucene项目的jsp

    3. **创建索引**:在JSP中编写代码来读取数据源(如文件或数据库),然后使用Lucene API建立索引。 4. **搜索索引**:实现用户输入查询后,通过JSP接收查询参数,调用Lucene的查询解析器和搜索器进行搜索。 5. **...

    Lucene---全文检索(文档pdf/txt/office/html)

    - **HTML**: Lucene 可以处理 HTML 文件,提取文本内容并进行索引。 ### 4. Lucene 的主要组件 - **Document**: 表示要索引的一份数据,可以包含多个字段(Field)。 - **Field**: 文档中的一个个属性,如标题、...

    Lucene.Net2.3源码,最新版

    NDoc 是一个用于生成 .NET 库文档的工具,此文件是 Lucene.Net 2.3.1 版本的输入文件,包含关于库的 XML 注释,NDoc 将这些注释转换成可读的 HTML 文档。 通过深入学习和理解这些源代码文件,开发者可以更好地掌握...

    lecene.net 对多种文件索引并搜索

    在Lucene.NET中,索引的过程包括创建一个索引Writer对象,打开目标目录,然后逐个读取文件,使用解析器提取内容,创建Document对象,并添加Field(字段)来表示每个文档的属性。索引完成后,可以通过优化操作来提高...

    lucene 小资源

    5. **搜索(Searching)**:用户输入查询后,Lucene通过查询解析器(QueryParser)生成查询对象,然后使用搜索器(Searcher)在索引中查找匹配的文档。 学习Lucene的过程中,你还需要掌握如何创建和管理索引,如何...

    lucene开发WEB搜索引擎

    爬虫可以使用C#的HttpClient、HtmlAgilityPack等库来实现,抓取网页的HTML并存储为文本文件。 2. 文本预处理:使用LUCENE.NET的分析器对收集到的网页内容进行预处理,包括分词、去除停用词、词形还原等。例如,可以...

    Lucene搜索技术

    5. **索引更新策略**:Lucene创新性地通过创建小索引文件并定期合并,提高索引效率,减少对IO操作的影响。 Lucene的API包含多个包,各自负责不同的功能: - **org.apache.lucene.search**:作为搜索的入口,提供...

    lucene.net及.net爬虫实现的简单搜索引擎

    其核心特性包括分词、评分、过滤和排序等,支持多种数据源的索引,如文件系统、数据库等。 .NET爬虫,又称网络抓取或网络蜘蛛,是一种自动化程序,用于从互联网上抓取大量信息。在本项目中,我们将使用.NET框架来...

    lucene实现站内检索

    在创建索引的过程中,Lucene会对文本进行分词,然后为每个文档生成一个由关键词及其位置组成的索引项。在搜索时,它会将用户输入的查询与索引进行匹配,返回最相关的文档。 在描述中提到,项目使用了Paoding ...

    LUCENE资料

    Lucene 支持对各种文本格式的数据进行索引,如 HTML、PDF 等,只要能将这些文件转换成文本,就能利用 Lucene 进行高效检索。由于其开源和跨平台的特性,Lucene 已广泛应用于各种搜索应用程序,例如 Eclipse 的帮助...

    Lucene 在知识库全文检索模块中所起的作用

    - 从描述中的层级图来看,Lucene 在 CIS 系统中位于用户和数据库之间,负责处理从不同源获取的文件和数据,生成索引,然后进行全文搜索。 - 0 层代表用户接口,1.1 层至 1.5 层分别对应 TXT/HTML、Word、PDF、二...

Global site tag (gtag.js) - Google Analytics