您的位置:首页 > 其它

Lucene学习-创建索引(一)

2010-05-09 20:26 337 查看
Lucene创建索引的过程如下:

1) 建立索引器IndexWriter

2)建立文档对象Document

3)建立信息字段对象Field

4)将Field添加到Document中

5)将Document添加到IndexWriter中

6)关闭索引器IndexWriter

创建Field:Field field=new Field(Field名称,Field内容,存储方式,索引方式);

创建Document:Document doc=new Document();

将Field添加到Document中:doc.add(field)

创建IndexWriter:IndexWriter writer=new IndexWriter(存储索引的路径,分析器的实例);

将Docment添加到IndesWriter中:writer.addDocument(doc);

关闭索引器:writer.close();

创建索引实例:

//为文件创建索引
package tool;

import java.io.*;
import tool.FileText;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.analysis.standard.StandardAnalyzer;

public class FileIndex {

/**
* @param args
*/
public static void main(String[] args) throws java.io.IOException {
// 设定索引文件的存放路径,为程序的同级目录下的file文件
String indexPath = "F:/DocumentIndex";
// 创建IndexWriter
IndexWriter writer = new IndexWriter(indexPath, new StandardAnalyzer());
// 创建Document
Document doc = new Document();
File f = new File("F:/doc/a.htm");

// 创建Field-name
String name = f.getName();
Field field = new Field("name", name, Field.Store.YES,Field.Index.TOKENIZED);
// 添加field
doc.add(field);

// 创建Field-content
String content = FileText.getText(f);
field =new Field("content",content,Field.Store.YES,Field.Index.TOKENIZED);
//添加field
doc.add(field);

//创建Field-path
String path=f.getPath();
field=new Field("path",path,Field.Store.YES,Field.Index.TOKENIZED);
//添加field
doc.add(field);

//添加 document
writer.addDocument(doc);

//*****************************************/
doc=new Document();
f=new File("F:/doc/b.htm");

//创建Field-name
name=f.getName();
field=new Field("name",name,Field.Store.YES,Field.Index.TOKENIZED);
//添加field
doc.add(field);

//创建Field-content
content=FileText.getText(f);
field=new Field("content",content,Field.Store.YES,Field.Index.TOKENIZED);
//添加field
doc.add(field);
//创建Field-path;
path=f.getPath();
field=new Field("path",path,Field.Store.YES,Field.Index.TOKENIZED);
//添加field
doc.add(field);

//添加Document
writer.addDocument(doc);

//关闭IndexWriter
writer.close();
//提示
System.out.println("File Index Created!");
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: