Lucene 2.0 建立索引 与 1.4区别

Lucene初试——关于大文本建立索引和中文乱码以及QueryParser检索的一些体会 这几天因为一个小项目用到Lucene,于是去学习了一下,现在还有很多地方没有了解,先就我遇到的问题做下总结。 一、大文本建索引问题 我这里说的大文本,实际上也就200M左右的txt,或许不应该成为大文本,但是我在建索引时遇到200M左右的的确导致了内存溢出,报错误java.lang.OutOfMemoryError: Java heap space ,到网上查了很久,试了一些方法,比如修改JV 阅读详情

建立索引的过程:

package org.apache.lucene;
import  org.apache.lucene.index.*;
import org.apache.lucene.analysis.standard.*;
import org.apache.lucene.document.*;
import java.io.*;
import java.util.Date;
//import org.apache.lucene.store.*;;
/**
 * @author cao
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
public class Indexer {

 public static void main(String[] args) throws Exception{
  if (args.length != 2){
   throw new Exception ("usage: java " + Indexer.class.getName() + "<index dir> <data dir>");
  }
  File indexDir = new File(args[0]);      //在指定的目录创建索引
  File dataDir = new File(args[1]);       //索引此目录下的文件
  
  long start = new Date().getTime();
  int  numIndexed = index(indexDir, dataDir);
  long end = new Date().getTime();
  System.out.println("Indexing " + numIndexed + " files took " + (end - start ) + " milliseconds");
 }
  
 public static int index(File indexDir, File dataDir) throws IOException {
  if (!dataDir.exists() || !dataDir.isDirectory()){
   throw new IOException(dataDir + "does not exit or is not a directory");
   }
  IndexWriter writer = new IndexWriter(indexDir , new StandardAnalyzer(),true);
  writer.setUseCompoundFile(false);
  indexDirectory(writer,dataDir);
  int numIndexed = writer.docCount();
  writer.optimize();                                            //索引优化
  writer.close();                                                  //关闭索引
  return numIndexed;
 }
 
 private static void indexDirectory(IndexWriter writer , File dir) throws IOException{
  File[] files = dir.listFiles();
  for(int i = 0; i < files.length; i++){
   File f = files[i];
   if(f.isDirectory()){
    indexDirectory(writer,f);    
   }else if(f.getName().endsWith(".txt")){
    indexFile(writer,f);
   }
  } 
 }
 
//  method to actually index a file using Lucene
 private static void indexFile(IndexWriter writer, File f)
 throws IOException {
  if (f.isHidden() || !f.exists() || !f.canRead()) {
   return;
  }
 System.out.println("Indexing " + f.getCanonicalPath());
 Document doc = new Document();
 //doc.add(Field.Text("contents", new FileReader(f)));                               //Lucene 1.4 调用方法
 //doc.add(Field.UnIndexed("filename", f.getCanonicalPath()));              //Lucene 1.4 调用方法

   Reader reader = new BufferedReader(new FileReader(f));  
 doc.add(new Field("contents",reader));
 doc.add(new Field("filename", f.getCanonicalPath(),Field.Store.YES,Field.Index.TOKENIZED));
 writer.addDocument(doc);
 }
 

 

以下是转贴: 1.4 和 2.0 区别:

// 创建索引

    public void indexFiles() {

        // 创建索引文件存放路径

        File indexDir = new File("E://lucene_Learning//lucene-2.0.0src//src//demo//index");

 

        try {

            Date start = new Date();

            // 创建分析器,主要用于从文本中抽取那些需要建立索引的内容,把不需要参与建索引的文本内容去掉.

            // 比如去掉一些a the之类的常用词,还有决定是否大小写敏感.

            StandardAnalyzer standardAnalyzer = new StandardAnalyzer();

            // 参数true用于确定是否覆盖原有索引的

            IndexWriter indexWriter = new IndexWriter(indexDir, standardAnalyzer, true);

            indexWriter.setMergeFactor(100);

            indexWriter.setMaxBufferedDocs(100);

            // 只索引这个Field的前5000个字,默认为10000

            indexWriter.setMaxFieldLength(5000);

            // 从数据库取出所有纪录

            List articleList = articleManager.getArticles(null);

            for (int i = 0; i < articleList.size(); i++) {

                Article article = (Article) articleList.get(i);

                // Document方法是创建索引的具体代码

                Document doc = Document(article);

                indexWriter.addDocument(doc);

            }

            // Optimize的过程就是要减少剩下的Segment的数量,尽量让它们处于一个文件中.

            indexWriter.optimize();

            indexWriter.close();

            Date end = new Date();

            System.out.println("create index: " + (end.getTime() - start.getTime()) + " total milliseconds");

        } catch (IOException e) {

            System.out.println(" caught a " + e.getClass() + "/n with message: " + e.getMessage());

        }

    }

    public static Document Document(Article article)

            throws java.io.IOException {

        Document doc = new Document();

        // article表的主健创建索引,关于Field的几个参数下面有详细解释

        Field fieldId = new Field("uid", article.getArticleId(), Field.Store.YES, Field.Index.UN_TOKENIZED, Field.TermVector.YES);

        // detail字段创建索引,detailDB中是clob字段,内容为html文本

        String contentHtml = article.getDetail();

        Reader read = new StringReader(contentHtml);

        // HTMLParserdetail字段中的HTML分析成文本在索引

        // HTMLParser这个类可以在lucenedemo中找到

        HTMLParser htmlParser = new HTMLParser(read);

        BufferedReader breader = new BufferedReader(htmlParser.getReader());

        String htmlContent ="";

        String tempContent = breader.readLine();

        while (tempContent != null && tempContent.length() > 0) {

            htmlContent = htmlContent + tempContent;

            tempContent = breader.readLine();

        }

        Field fieldContents = new Field("content", htmlContent,

                Field.Store.COMPRESS, Field.Index.TOKENIZED,Field.TermVector.YES);

        // db中的每条纪录对应一个doc,每个字段对应一个field

        doc.add(fieldId);

        doc.add(fieldContents);

        return doc;

    }

    // 搜索文件,keyword是你在页面上输入的查找关键字,这里查找的是detail字段

    public List searchFiles(String keyword){

        String index = "E://lucene_Learning//lucene-2.0.0src//src//demo//index";

        // hitsList用来保存db的纪录,这些纪录可以通过查询结果取到

        List hitsList = new ArrayList();

        try {

            Date start = new Date();

            IndexReader reader = IndexReader.open(index);

            Searcher searcher = new IndexSearcher(reader);

            Analyzer analyzer = new StandardAnalyzer();

            QueryParser parser = new QueryParser("content", analyzer);

            // 解析查询关键字,比如输入的是以空格等分开的多个查询关键字,这里解析后,可以多条件查询

            Query query = parser.parse(keyword);

            // hits用来保存查询结果,这里的hits相当于sql中的result

            Hits hits = searcher.search(query);

            for (int i = 0; i < hits.length(); i++) {

                Document doc = hits.doc(i);

                // 获得article表的主健

                String id = doc.get("uid");

                // 根据主健去db中取纪录,返回到hitsList

                try {

                    Article article = articleManager.getArticle(id);

                } catch (ObjectRetrievalFailureException e) {

                    article = null;

                }

                       // 如果没有找到该纪录,表示该纪录已经不存在,不必添加到hitsList

                if(article!=null)  hitsList.add(article);

            }

            searcher.close();

            reader.close();

            Date end = new Date();

            System.out.println("search files: " + (end.getTime() - start.getTime()) + " total milliseconds");

        } catch (IOException e) {

            System.out.println(" caught a " + e.getClass() + "/n with message: " + e.getMessage());

        } catch (ParseException e) {

            System.out.println(" caught a " + e.getClass() + "/n with message: " + e.getMessage());

        }

        return hitsList;

    }

    // 删除索引

    public void deleteIndex(){

        String index = "E://lucene_Learning//lucene-2.0.0src//src//demo//index";

        try {

            Date start = new Date();

            IndexReader reader = IndexReader.open(index);

            int numFiles = reader.numDocs();

            for (int i = 0; i < numFiles; i++) {

                // 这里的删除只是给文档做一个删除标记,你可以看到执行deleteDocument后会产生一个del后缀的文件,

                // 用来记录这些标记过的文件

                reader.deleteDocument(i);

            }

            reader.close();

            Date end = new Date();

            System.out.println("delete index: " + (end.getTime() - start.getTime()) + " total milliseconds");

        } catch (IOException e) {

            System.out.println(" caught a " + e.getClass() + "/n with message: " + e.getMessage());

        }

 

    }

    // 恢复已删除的索引

    public void unDeleteIndex(){

        String index = "E://lucene_Learning//lucene-2.0.0src//src//demo//index";

        try {

            IndexReader reader = IndexReader.open(index);

            reader.undeleteAll();

            reader.close();

        } catch (IOException e) {

            System.out.println(" caught a " + e.getClass() + "/n with message: " + e.getMessage());

        }

 

}

 

Field就像我们学过的数据库中的字段,简单的说,就是一个名值对。这个域有三种属性,分别是

isStored - 是否被存储
isIndexed -
是否被索引
isTokenized -
是否分词

这些属性的组合又构成了四种不同类型的Field,而且各有用途

 

Stored

Indexed

Tokenized

Keyword

Y

Y

N

UnIndexed

Y

N

N

UnStored

N

Y

Y

Text: String

Y

Y

Y

Text : Reader

N

Y

Y

 

关于Field2.0.0版本和1.4.3版本方法相比改动比较大,具体见下表

 

1.4.3版本中的下面方法都被Field(String name, String value, Store store, Index index, TermVector termVector)取代

Keyword(String name, String value) // only version 1.4.3
存储、索引、不分词,用于URI(比如MSN聊天记录的日期域、比如MP3文件的文件全路径等等)
Field(String name, String value,
Field.Store.YES, Field.Index.UN_TOKENIZED) // version 2.0.0

UnIndexed(String name, String value) // only version 1.4.3
存储、不索引、不分词,比如文件的全路径
Field(String name, String value,
Field.Store.YES, Field.Index.NO) // version 2.0.0

UnStored(String name, String value) // only version 1.4.3
不存储、索引、分词,比如HTML的正文、Word的内容等等,这部分内容是要被索引的,但是由于具体内容通常很大,没有必要再进行存储,可以到时候根据URI再来挖取。所以,这部分只分词、索引,而不存储。
Field(String name, String value,
Field.Store.YES, Field.Index.TOKENIZED)// version 2.0.0

Text(String name, String value) // only version 1.4.3
存储、索引、分词,比如文件的各种属性,比如MP3文件的歌手、专辑等等。Field.Store.YES, Field(String name, String value,Field.Index.TOKENIZED)// version 2.0.0

Text(String name, Reader value) // only version 1.4.3

Field(String name, Reader reader)  // version 2.0.0
不存储、索引、分词。



Lucene 4 和 Solr 4 学习笔记(3) 当初说要写写lucene和solr的学习笔记,写了两个后就懒得写了。最近想做个lucene和solr的中文学习网站,翻译一些lucene和solr的英文资料,并提供一个中文的交流学习平台。所以想把这个系列继续下去。     言归正传,上面说到我们的目标是学习和修改lucene/solr的源代码。不过如果我们从没有用过,那是不可能读懂源代码的。这里推荐《lucene in action》第二版,中 阅读详情

相关推荐

yolov11使用记录(训练自己的数据集)

本文介绍了如何安装和使用Ultralytics YOLOv11进行目标检测。首先,通过Anaconda创建并激活虚拟环境,安装必要的依赖库如PyTorch和Ultralytics。接着,从GitHub下载YOLOv11源码,并在PyCharm中配置环境。下载预训练的YOLOv11模型后,通过编写简单的Python脚本进行图片检测,验证环境配置的正确性。最后,文章提到可以基于此环境训练自定义模型。整个过程涵盖了从环境搭建到模型应用的完整流程,适合初学者快速上手YOLOv11

IT菜鸟 7465

lucene.net 2.9.2 实现索引生成,修改,查询,删除实例

lucene.net 2.9.2 实现索引生成,修改,查询,删除实例

Matlab实战:用Transformer+LSTM+SVM搞定股票价格预测(附完整代码)

本文介绍了一种基于Transformer、LSTM和SVM的混合建模方法,用于股票价格预测。该方法结合了Transformer的全局依赖捕捉能力、LSTM的时序特征提取优势以及SVM的非线性回归能力,有效应对金融时间序列的非平稳性和噪声问题。文章提供了完整的Matlab实现代码,并展示了混合模型在实盘测试中的优异表现,方向预测准确率达62%,最大回撤控制在3.2%以内。

milk8的博客 238

关于lucene2.0的创建、检索和删除功能的完整实现

文章来源:http://blog.csdn.net/xiaodaoxiao ... /09/10/1203959.aspx   最近要做一个站内的全文检索功能,主要是针对clob字段的,于是去网上找了点lucene的资料,现在新版本的是2.0.0,网上的例子多是1.4.3的,有些方法已经废弃了,搞了n久终于把2.0.0的功能实现了,呵呵,下面把实现的代码贴出来,实现了索引的创建、检索和删除功能,并...

wuqinlss的博客 138

如何使用lucene对文档进行删除操作

在使用lucene创建索引库中,介绍了一些基础的lucene概念,如何用lucene进行删除操作呢。 /** *根据查询条件进行删除 */ private static void testDeleteDocumentByQueryTerm()throws Exception { IndexWriter indexWriter = new IndexWriter( FSDirectory.open(new File("J:\\storeSpace\\l

wb785074651的博客 631

解决lucene更新删除无效的问题

个人博客 地址:http://www.wenhaofan.com/article/20180921233809 问题描述在使用deleteDocuments,updateDocument方法根据id字段删除更新索引时不抛异常但是删除更新失败writer.deleteDocuments(new Term("id", "1"));解决问题 在创建索引时使用到了lucen...

dici2748的博客 417

Lucene整理--索引建立

创建索引的过程如下: (1)、建立索引IndexWriter,这相当于一本书的框架 (2)、建立文档对象Document,这相当于一篇文章 (3)、建立信息字段对象Field,这相当于一篇文章中的不同信息(标题、正文等)。 (4)、将Field添加到Document里面。 (5)、将Document添加到IndexWriter里面。 (6)、关闭索引IndexWriter

曹海成的专栏 4532

亲测,java lucene建立索引,读取索引

/** * 创建索引文件 触发更新数据库搜索文件 * @param contents 建立索引内容数据 * @param searchDir 索引文件目录 */ public static void createIndex(List<Content> contents, String searchDir, boolean hasDelete) { IndexWr...

admin123fy的博客 859

lucene索引结构分析

<br />Lucene是一个优秀的开源全文搜索项目,很多项目的搜索模块都是使用Lucene。<br />例如大名鼎鼎的eclipse的帮助系统就是使用的Luence作为起做索引的内核。<br />Lucene良好的体系结构使得其API接口非常方便易用,使得非自然语言处理的专业人员可以不用关心内部的索引结构,也可以很快的搭建起一个搜索引擎。但是对于高级用户和专业人员,了解其背后使用的索引结构也是必不可少的。 <br />在研究生阶段,我自己也弄了一个索引结构,好奇心促使我将Luence的索引结构和自己的索引

solotraveler 5727

lucene 添加扩展词需要重新索引_5分钟了解lucene全文索引

一、Lucene介绍及应用Apache Lucene是当下最为流行的开源全文检索工具包,基于JAVA语言编写。目前基于此工具包开源的搜索引擎,成熟且广为人知的有Solr和Elasticsearch。2010年后Lucene和Solr两个项目由同一个Apache软件基金会的开发团队制作,所以通常我们看到的版本都是同步的。二者的区别Lucene是工具包,而Solr是基于Lucene制作的企业级搜索应...

weixin_39628342的博客 216

lucene java 实例_LUCENE简单实例

关键字: lucene说明一下,这一篇文章的用到的lucene,是用2.0版本的,主要在查询的时候2.0版本的lucene以前的版本有了一些区别.其实这一些代码都是早几个月写的,自己很懒,所以到今天才写到自己的博客上,高深的文章自己写不了,只能记录下一些简单的记录点滴,其中的代码算是自娱自乐的,希望高手不要把重构之类的砸下来...1、在windows系统下的的C盘,建一个名叫s的文件夹,在...

weixin_29306011的博客 470

Lucene 索引文件的读取(十二)之doc&&pos&&pay

在前几篇索引文件的读取的系列文章中,我们介绍索引文件tim&&tip的读取时机点时说到,在生成StandardDirectoryReader对象期间,会生成SegmentReader对象,该对象中的FieldsProducer信息描述了索引文件tim&&tip、索引文件doc、索引文件pos&&pay中所有域的索引信息,故我们从本篇文章开始介绍索引文件.doc、.pos、.pay的读取。 索引文件.doc的数据结构(Lucene 8.4.0)   在文章索

q364367207的专栏 351

lucene中document的所有id_5分钟带你了解Lucene全文索引

一、Lucene介绍及应用Apache Lucene是当下最为流行的开源全文检索工具包,基于JAVA语言编写。目前基于此工具包开源的搜索引擎,成熟且广为人知的有Solr和Elasticsearch。2010年后Lucene和Solr两个项目由同一个Apache软件基金会的开发团队制作,所以通常我们看到的版本都是同步的。二者的区别Lucene是工具包,而Solr是基于Lucene制作的企业级搜索应...

weixin_27531501的博客 278

Sphinx(狮身人面)lucene还牛的搜索引

Sphinx(狮身人面)lucene还牛的搜索引擎 Sphinx是一个俄国人开发的搜索引擎,Sphinx建索引速度是最快的,比Lucene快9倍以上。因此,Sphinx非常适合做准实时搜索引擎。[亿级数据的高并发通用搜索引擎架构设计]http://hi.baidu.com/zhizhesky/blog/item/0fae4036f5db8dd2a2cc2b4f.html它的主要特点是: 一、性能非常出色 150万条记录一两分钟就索引完毕,2-4GB以内的文本检索速度不到0.1秒钟。ferret也

minothing的专栏 1万+

lucene基础知识

注:在MyEclipse中可以通过Ctrl+Shift+R和通配符查询相关的资源。 1、全文检索的概念 <1>从大量的信息中快速、准确地查找出要的信息。 <2>搜索的内容是文本信息(不是多媒体)。 <3>根据文本的关键词进行搜索,而不是根据语义进行搜索。 <4>全面、快速、准确是衡量全文检索系统的关键指标。 <5>搜索时英文不区分大小写。 <6>结果列表由相关度排序。 <7>全文搜索有站内搜索和垂直搜索 2、全文搜索数据搜

woaini886353的博客 1380

5分钟了解lucene全文索引

一、Lucene介绍及应用 Apache Lucene是当下最为流行的开源全文检索工具包,基于JAVA语言编写。 目前基于此工具包开源的搜索引擎,成熟且广为人知的有Solr和Elasticsearch。2010年后Lucen...

259

Lucene创建索引搜索索引试手

由于仿写的源码的版本是Lucene2.1.0,我用的Lucene已经是4.5.0了,所以像创建IndexWriter、IndexSearcher的时候源码的已经不能用了,只好自己查api摸索,所以有个老师在旁边指导该多好。 首先我创建的是中文的索引。 CJKAnalyzer是:对中文汉字,每两个字作为一个词条 StandardAnalyzer是:单个汉字作为一个词条 ...

aigui1439的博客 131

lucene中document的所有id_5分钟了解lucene全文索引

摘要:本文通俗地介绍了Lucene全文检索的内容及工作原理,以及索引的结构,旨在让以前未了解过Lucene的读者在能在短时间内对Lucene有简单认知,未介绍具体代码,读完本文可知道Lucene是什么,有哪些具体应用,我们一直说的索引是什么。一、Lucene介绍及应用Apache Lucene是当下最为流行的开源全文检索工具包,基于JAVA语言编写。目前基于此工具包开源的搜索引擎,成熟且广为人知的...

weixin_42098892的博客 221

Lucene全文检索之倒排索引实现原理、API解析【2018.11

》 官网 http://lucene.apache.org/ 下载地址:https://mirrors.tuna.tsinghua.edu.cn/apache/lucene/java/7.5.0/ 》 Lucene的全文检索是指什么: 程序扫描文档,对文档document建立索引,并对文档进行分词 ik,对每一个词建立索引并关联文档document的编号(索引); 当用户进行搜索时候,按照搜...

Syntacticsugar's blog 819

YOLOv8垃圾分割检测系统.zip

YOLOv8垃圾分割检测系统.zip

上一篇: 生活和工作计划
下一篇: lucene 排序算法思路
tattarrattat
博客等级 码龄20年 180粉丝 90原创
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值