lucene学习-建立索引

   本文的lucene是基于lucene3.5版本.java

   使用lucene实现搜索引擎开发,核心的部分是创建索引和搜索。本节主要是记录建立索引部分的内容。app

   建立的索引结构如图所示。搜索引擎

   

 

建立索引的步骤分为如下几个步骤:orm

一、创建索引器IndexWriter对象

二、建立文档对象Documentblog

三、创建信息对象字段Field索引

四、将Field对象添加到Document内存

五、将Document对象添加到IndexWriter对象中开发

下面简要介绍几个核心对象。文档

(1)、建立IndexWriter对象。

IndexWriter writer=new IndexWriter(directory, iwc)。

directory是建立的索引要保存的路径,若是要保存在硬盘中则使用Directory directory = FSDirectory.open(new File(path))建立一个directory对象。

若是要保存在内存中则使用:RAMDirectory directory=new RAMDirectory()建立一个directory对象。

(2)、建立Document对象。

Document doc =new Document();建立了一个不含有任何Field的空Document,若是要要Field添加到Document中,则使用add(Field)方法便可实现。

doc.add(field)。

(3)、建立Field对象。

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

存储方式分为3种:一、彻底存储(Field.Store.YES);二、不存储(Field.Store.NO);三、压缩存储(Field.Store.COMPRESS)。

索引方式分为4种:一、不索引(Field.Index.NO);二、 Field.Index.ANALYZED ;三、 Field.Index.NOT_ANALYZED;四、Field.Index.NOT_ANALYZED_NO_NORMS

建立一个简单的索引程序代码以下所示:

public void Index() {
		String[] ids = { "1", "2", "3", "4" };
		String[] names = { "aa", "bb", "cc", "dd" };
		String[] contents = {
				"Using AbstractJExcelView to export data to Excel file via JExcelAPI library",
				"Using AbstractPdfView to export data to Pdf file via Bruno Lowagie’s iText library. ",
				"Example to integrate Log4j into the Spring MVC application. ",
				"Using Hibernate validator (JSR303 implementation) to validate bean in Spring MVC. " };
		IndexWriter writer = null;
		try {
			Directory directory = FSDirectory.open(new File(path));
			// RAMDirectory directory=new RAMDirectory();
			IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_35,
					new StandardAnalyzer(Version.LUCENE_35));
			writer = new IndexWriter(directory, iwc);
			Document doc = null;
			for (int i = 0; i < ids.length; i++) {
				doc = new Document();
				doc.add(new Field("id", ids[i], Field.Store.YES,
						Field.Index.NOT_ANALYZED_NO_NORMS));
				doc.add(new Field("name", names[i], Field.Store.YES,
						Field.Index.NOT_ANALYZED_NO_NORMS));
				doc.add(new Field("contents", contents[i], Field.Store.YES,
						Field.Index.ANALYZED));
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				doc.add(new Field("date", sdf.format(new Date()),
						Field.Store.YES, Field.Index.NOT_ANALYZED));
				// Field.Index.ANALYZED;

				writer.addDocument(doc);
				writer.commit();
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (writer != null) {
				try {
					writer.close();
				} catch (CorruptIndexException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
相关文章
相关标签/搜索