搜索引擎的学习2

来源:互联网 发布:java毕业论文开题报告 编辑:程序博客网 时间:2024/05/18 21:38

1.      Lucene的Document

Document直译为文档,在Lucene中,它是一种逻辑文件,Lucene无法对物理文件建立索引,只能处理和识别document类型的文件,因此我们就可以将一个Document与一个物理文件对应,用它来表示物理文件,但是更多的时候Document和物理文件没有关系,它是一种数据源的集合,它是向Lucene提供原始索引的文本内容。对应关系可以如下表示:


Document与多个数据源


Document与多个文档的数据的数据源

2.Field

         在Lucene中,数据源是由一个被称为Field的类来表示的,我们可以把它理解为字段或者是属性,如;field1表示主题,field2表示文件内容,field3表示创建时间,等等。

         数据源的各种属性,其实就是:

1)  是否存储;

2)  是否索引;

3)  是否分词;

在field内有Store和Index两个静态的内部类,Store类有3个公有的静态属性

 Store.No:表示field不需要存储; Store.YES:表示field需要存储; Stroe.COMPASS:表示使用压缩方式来保存这个Field值。

Index类有4个公有的静态属性:

Index.NO:表示该Field不需要索引,用户不需要去查询改Field的值;Index.TOKENIZED:表示该Field先被分词在索引;
Index.UN_TOKENIZED:表示不对该Field进行分词,但是要对它进行索引,用户对改Field进行查找;
Index.NO_NORMS:表示对改Field进行索引,但是不使用Analyzer,同时禁止它参加评分,以较少内存的消耗。


Lucene的索引工具IndexWriter

         在用户构建完Document并为其添加合适的Field后,可以通过IndexWriter可以很方便地将构建好的Document加入索引中。

         查看文档和源码就发现IndexWriter的构造函数如下:

Public IndexWriter(String path , Analyzer a, Boolean create)Public IndexWriter(File path , Analyzer a ,Boolean create)Public IndexWriter(Directory d , Analyzer a, Boolean create)


可以看出,3个构造函数就第一参数不一样,String是绝对路径,File是包装后的绝对路径,Directory是Lucene内部一种目录表示方式。

         第二个Analyzer是索引中的一个很重要的组成部分,即分词器,有默认的如处理英文的StandardAnalyzer等,其中中文分词的有“极易”,“庖丁”以及中科院的有语意功能的分词器等。

         第三个boolean就是指定是否将创建的索引删除重新构建,一般,第一次建索引时将它设置为true,之后将它设置为false。

         参看源码后,IndexWriter的实现流程基本如下:

 

向索引添加文档

         IndexWriter准备好了就可以向索引目录中添加Document,函数如下:

Publicvoid addDocument(Document doc)Publicvoid addDocument(Document doc,Analyzer analyzer)

<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);"></span>

实例如下:

Document bookdoc=new Document();Field price=new Field(“price”,”25.00”,Filed.Store.YES,Field.Index.NO);Bookdoc.add(price); IndexWriter writer = newIndexWriter(path,new StandardAnalyzer(),true);//向索引中加入图书价格构建的Document对象writer.addDocument(bookdoc);//只有关闭索引器,I/O缓存才会写到磁盘上writer.close();

Document bookdoc=new Document();

Field price=new Field(“price”,”25.00”,Filed.Store.YES,Field.Index.NO);

Bookdoc.add(price);

 

IndexWriter writer = newIndexWriter(path,new StandardAnalyzer(),true);

//向索引中加入图书价格构建的Document对象

writer.addDocument(bookdoc);

//只有关闭索引器,I/O缓存才会写到磁盘上

writer.close();

0 0