Lucene4.0 入门学习

一.简介
    
来看看官方文档是怎么描述lucene的:Lucene is a Java full-text search engine. Lucene is not a complete application, but rather a code library and API that can easily be used to add search capabilities to applications.
    简单描述一下:lucene是一个基于Java的全文搜索引擎,开发者根据API调用,开发出符合自己要求的搜索引擎。

二.基本概念
    对于刚刚接触luence的人来说,了解基本的概念是很有必要的,不至于对所有的东西都一头雾水。
    1.Analyze:分词器,要搜索,肯定要对搜索的内容进行分词吧。
    2.Directory:目录,即文件夹所在位置。
    3.IndexWriter:索引输出流,用来在制定目录创建索引文件。
    4.Document:源,索引是以源为单位进行索引的。
    5.Field:信息域,存储数据的最小单位,多个信息域组成一个源。
    6.DirectoryReader:用来读入索引文件流。
    7.IndexSearcher:搜索神器,用来搜索索引。
    8.Query:搜索的内容对象。

三.简单流程
    
使用lucene分两个部分:1.建立索引 2.搜索内容
    建立索引的主要操作:创建源(Document),源相当于一条数据库中的一条记录,往源中添加信息域(Field),信息域相当于条记录的一个字段。然后再将源放到IndexWriter中,即可创建索引。
    搜索内容:调用QueryParser.parse()方法,用字符串等创建一条搜索内容,接着创建一个IndexSearcher对象,并调用search()方法,将Query放到当中去,完成搜索功能。

四.HelloWorld代码

    Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_CURRENT);

    //将索引存放到内存中
    Directory directory = new RAMDirectory();
    //若要将索引存放到磁盘上,使用下面语句
    //Directory directory = FSDirectory.open("路径");
    IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_CURRENT, analyzer);
    IndexWriter iwriter = new IndexWriter(directory, config);
    Document doc = new Document();
    String title = "标题";
    String content = "被索引的内容";
    doc.add(new Field("title", title, TextField.TYPE_STORED)); 
    doc.add(new Field("content",content,TextField.TYPE_STORED));  iwriter.addDocument(doc); 
    iwriter.close();
    
    //搜索索引
    DirectoryReader ireader = DirectoryReader.open(directory);
    IndexSearcher isearcher = new IndexSearcher(ireader);
    //搜索content
    QueryParser parser = new QueryParser(Version.LUCENE_CURRENT, "content", analyzer);
    Query query = parser.parse("内容");
    //搜索结果取1000个
    ScoreDoc[] hits = isearcher.search(query, null, 1000).scoreDocs;
    //结果总数
    System.out.println(hits.length);
    for (int i = 0; i < hits.length; i++) {
      Document hitDoc = isearcher.doc(hits[i].doc);
      System.out.println("搜索结果 :" + hitDoc.get("title"));
    }
    ireader.close();
    directory.close();

以上代码需要导入的包有:lucene-core-4.0.0.jar  lucene-analyzers-common-4.0.0.jar  lucene-queryparser-4.0.0.jar

五.个人总结
    学习lucene是因为学校的课程设计,为此昨天下午看了很多其他人的入门博客,进展并不是很大,今天早上看了官方的文档来学习,速度很快,也有昨天已经做了点东西的原因。这也是我第一次看文档来学习吧,这个真心很重要,如马士兵老师说的,这个是一手鞋,以后学习还是不要二手鞋了,博文只是用来总结学习的内容,并不是用来学习的。之所以在博文的标题中标注4.0,是因为昨天看到很多老博文用的是3.6或者是2.2版本的,很多方法还是有差异的,而今天所用的是4.0特此表明。附上昨日做的简单文本搜索引擎,可以做课程设计的参考:http://vdisk.weibo.com/s/ixtMm

你可能感兴趣的:(入门,lucene4.0)