




18
我们首先在d:\lucene\s下放置了几个txt文件作为索引的源。创建d:\lucene\index作为索引文件的存放地址。当然还需要引入lucene3.0的包。具体步骤简介如下:
1、创建Directory对象(参数是存放索引的File类型,根据File的存放地点选择创建类)
2、创建indexWriter对象,参数(Directory对象,分词器,是否创建,分词的最大值)
3、获取源文件的File数组
4、通过循环将每个文件写入索引。
{
创建Document对象,并创建Field对象(列名称(文件名、内容等)),将Field加入到Dcument中,通过IndexWriter.addDocument(Document)写入索引中。
}
5、关闭indexWriter。
源码:
[CODE=java]
package com.hector.firstlucene;
/**********************
*
* @author Hector
* 建立索引 lucene3.0
*/
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Date;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.DateTools;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.SimpleFSDirectory;
import org.apache.lucene.util.Version;
public class TextFileIndexer {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
//保存索引文件的地方
String indexDir = “d:\\lucene\\index”;
//将要搜索TXT文件的地方
String dateDir = “d:\\lucene\\s”;
IndexWriter indexWriter = null;
//创建Directory对象 ,FSDirectory代表待索引的文件存在磁盘上
Directory dir = new SimpleFSDirectory(new File(indexDir));
//创建IndexWriter对象,第一个参数是Directory,第二个是分词器,第三个表示是否是创建,如果为false为在此基础上面修改,第四表示表示分词的最大值,比如说new MaxFieldLength(2),就表示两个字一分,一般用IndexWriter.MaxFieldLength.LIMITED
indexWriter = new IndexWriter(dir,new StandardAnalyzer(Version.LUCENE_30),true,IndexWriter.MaxFieldLength.UNLIMITED);
File[] files = new File(dateDir).listFiles();
for (int i = 0; i < files.length; i++) {
Document doc = new Document();
//创建Field对象,并放入doc对象中
doc.add(new Field(“contents”, new FileReader(files[i])));
doc.add(new Field(“filename”, files[i].getName(),
Field.Store.YES, Field.Index.NOT_ANALYZED));
doc.add(new Field(“indexDate”,DateTools.dateToString(new Date(), DateTools.Resolution.DAY),Field.Store.YES,Field.Index.NOT_ANALYZED));
//写入IndexWriter
indexWriter.addDocument(doc);
}
//查看IndexWriter里面有多少个索引
System.out.println(“numDocs”+indexWriter.numDocs());
indexWriter.close();
}
}
[/CODE]
代码中Lucene相关名词:[Lucene相关名词解释]
本文永久链接地址:http://www.ourys.com/post/lucene_create_index.html
原创文章如转载,请注明:转载自IT元素 [ http://www.ourys.com ]
中文转码 乱码 二叉树 元标记 兼容 域名 层次遍历 数据库 模板类 正则表达式 爬虫 百度 软软的 链表 队列 Access Ajax Asp Asp.Net CSS Eclipse feedsky Google IIS IIS7 JAVA JavaScript jQuery JTBC linux Lucene MyEclipse Mysql Oracle Reseller Hosting SEO SQL SQL Server TinyMce Ubuntu Ubuntu9.04 Ubuntu9.10 Ubuntu10.04 Win7 WordPress Plugin
WP Cumulus Flash tag cloud by Roy Tanck and Luke Morton requires Flash Player 9 or better.