Lucene (一)建立索引及应用的属性详解

xiaoxiao2021-02-28  131

public class HelloLucene { //创建索引 public void index(){ IndexWriter writer = null; try { //1、创建目录Directory Directory directory = FSDirectory.open(new File("D:/testLucene/index"));//指定创建索引的目录 //2、创建IndexWriter IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_35, new StandardAnalyzer(Version.LUCENE_35)); writer = new IndexWriter(directory, iwc); //3、创建Document对象 Document document = null; //4、为Document添加Filed(Filed为Document对象的元素) File f = new File("d:/testLucene/allFile"); for(File file:f.listFiles()){ document = new Document(); //将文件的内容加入到document对象中 document.add(new Field("content", new FileReader(file))); //将文件的名字加入到document对象中(文件名、循环的文件名、存储(见下面详解)、不分词并建立索引) document.add(new Field("filename" , file.getName() , Field.Store.YES ,Field.Index.NOT_ANALYZED) ); document.add(new Field("path" , file.getAbsolutePath() , Field.Store.YES , Field.Index.NOT_ANALYZED)); //5、通过IndexWriter添加索引到文档中 writer.addDocument(document); } } catch (IOException e) { e.printStackTrace(); } finally { //关闭流 if(null != writer){ try { writer.close(); } catch (CorruptIndexException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } //测试 public static void main(String[] args) { HelloLucene lucene = new HelloLucene(); lucene.index(); } }

lucene在doc.add(new Field("content",curArt.getContent(),Field.Store.NO,Field.Index.TOKENIZED)); 

Field有两个属性可选:存储和索引。  通过存储属性你可以控制是否对这个Field进行存储;  通过索引属性你可以控制是否对该Field进行索引。  事实上对这两个属性的正确组合很重要。  Field.Index Field.Store 说明  TOKENIZED(分词) YES 被分词索引且存储  TOKENIZED NO 被分词索引但不存储  NO YES 这是不能被搜索的,它只是被搜索内容的附属物。如URL等  UN_TOKENIZED YES/NO 不被分词,它作为一个整体被搜索,搜一部分是搜不出来的  NO NO 没有这种用法  我们那文章表为例.articleinfo.有ID,title(标题),sumary(摘要),content(内容),userName(用户名)  其中title(标题),sumary(摘要)属于第一种情况,既要索引也要分词,也要存储.  content(内容)要分词,索引,但不存储.由于他太大了,而且界面也不用显示整个内容.  ID要存储,不用索引.因为没人用他来查询.但拼URL却很需要他.索引要存储.  userName(用户名)索引,但不分词.可用保存.为什么不分词?比如"成吉思汗",我不想被"成汉"搜索到.我希望要么"成吉思汗"或者"*吉思*"通配符搜到.  总结如下:  1.如果要对某Field进行查找,那么一定要把Field.Index设置为TOKENIZED或UN_TOKENIZED。TOKENIZED会对Field的内容进行分词;而UN_TOKENIZED不会,只有全词匹配,该Field才会被选中。  2.如果Field.Store是No,那么就无法在搜索结果中从索引数据直接提取该域的值,会使null。  补充:         Field.Store.YES:存储字段值(未分词前的字段值)         Field.Store.NO:不存储,存储与索引没有关系         Field.Store.COMPRESS:压缩存储,用于长文本或二进制,但性能受损         Field.Index.ANALYZED:分词建索引         Field.Index.ANALYZED_NO_NORMS:分词建索引,但是Field的值不像通常那样被保存,而是只取一个byte,这样节约存储空间         Field.Index.NOT_ANALYZED:不分词且索引         Field.Index.NOT_ANALYZED_NO_NORMS:不分词建索引,Field的值去一个byte保存         TermVector表示文档的条目(由一个Document和Field定位)和它们在当前文档中所出现的次数         Field.TermVector.YES:为每个文档(Document)存储该字段的TermVector         Field.TermVector.NO:不存储TermVector         Field.TermVector.WITH_POSITIONS:存储位置         Field.TermVector.WITH_OFFSETS:存储偏移量         Field.TermVector.WITH_POSITIONS_OFFSETS:存储位置和偏移量
转载请注明原文地址: https://www.6miu.com/read-83006.html

最新回复(0)