Luence5分钟快速入门示例

使用Lucene,可以非常方便给我们的应用增加上全文索引的功能,使用上也非常简单,只需要5分钟我们就可以学会如何使用它。

1、先从官方下载,现在的最新版本是4.4.0,下面的示例代码也是基于4.4的;

2、建立一个JAVA工程,将这些个jar从Lucene的目录中找出来:lucene-analyzers-common-4.4.0.jar、lucene-core-4.4.0.jar、lucene-queries-4.4.0.jar、lucene-queryparser-4.4.0.jar,并加入到工程的classpath中;

3、示例JAVA代码,为了简单好理解,示例是以将内存中加入一些字符串,并通过查询结果,再将结果显示出来。

1)、建立内容索引

//创建一个分析器,这里使用的是标准分析器,适用于大多数场景,并且在StandardAnalyzer中包括了部分中文分析处理功能,虽然其本身也有一个中文分析器ChineseAnalyzer,
//不过ChineseAnalyzer将会在5.0的版本中被去掉,使用StandardAnalyzer即可。
//另外在analyzers-common中,包括了针对很多种不同语言的分析器,其中包括中文分析器
Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_44);

//Directory是用于索引文件的存储的抽象类,其子类有将索引文件写到文件的,也有直接放到内存中的,这里的RAMDirectory就是放在内存中索引
//优点是速度快,缺少是不适合于大量数据的索引。这里的数据比较少,所以使用RAMDirctory非常适合。
//具体的可以查看Directory, RAMDirectory,FSDirectory等API说明,这里要强调一下的是FSDirectory是一个文件索引存储的抽象类,下面还有三个子类:MMapDirectory, NIOFSDirectory, SimpleFSDirectory,根据不同的操作系统及使用场景进行不同的选择了。
Directory index = new RAMDirectory();

//IndexWriterConfig包括了所有创建IndexWriter的配置,一旦IndexWriter创建完成后,此时再去修改IndexWriterConfig是不会影响到IndexWriter实例的,此时如果想获取正确的IndexWirter的配置,最好是通过IndexWirter.getConfig()方法了,另外IndexWriterConfig本身也是一个final类。
IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_44, analyzer);

//顾名思义,IndexWriter是用于维护及增加索引的
IndexWriter w = new IndexWriter(index, config);

addDoc(w, "Lucene in Action", "193398817");
addDoc(w, "Lucene for Dummies", "55320055Z");
addDoc(w, "Managing Gigabytes", "55063554A");
addDoc(w, "The Art of Computer Science", "9900333X");
w.close();
以下是addDoc方法的代码,功能是将内容加入到索引中
private static void addDoc(IndexWriter w, String title, String isbn) throws IOException {
  Document doc = new Document();
  doc.add(new TextField("title", title, Field.Store.YES));
  doc.add(new StringField("isbn", isbn, Field.Store.YES));
  w.addDocument(doc);
}

这里我们需要注意一下,增加标题索引使用的是TextField,增加isbn索引使用的是StringField,这两个都是IndexableField的子类,TextField表示是会被拆分并且被索引的字段,而StringField只会一个整体被索引,而不会进行拆分索引。

2)、查询通过读取命令行参数,并将其传给luence的QueryParset,再通过Query执行查询

String querystr = args.length > 0 ? args[0] : "lucene";
//通过查询解析器QueryParser创建一个查询Query.
//QueryParser是JavaCC(http://javacc.java.net)编译的其中最重要的方法就是QueryParserBase.parse(String),
//特别需要注意的是QueryParser不是线程安全的
Query q = new QueryParser(Version.LUCENE_44, "title", analyzer).parse(querystr);

3)、执行查询根据index创建IndexSearcher,然后TopScoreDocCollector就会返回查询的结果

//这个表示每次最多显示的结果数
int hitsPerPage = 10;
//创建索引读取器
IndexReader reader = IndexReader.open(index);
//创建索引查询器
IndexSearcher searcher = new IndexSearcher(reader);
//以TopDocs的方式返回最多hitsPerPage的查询结果
TopScoreDocCollector collector = TopScoreDocCollector.create(hitsPerPage, true);
//执行查询
searcher.search(q, collector);
ScoreDoc[] hits = collector.topDocs().scoreDocs;

4)、显示索引查询结果

System.out.println("Found " + hits.length + " hits.");
for(int i=0;i<hits.length;++i) {
    int docId = hits[i].doc;
    Document d = searcher.doc(docId);
    System.out.println((i + 1) + ". " + d.get("isbn") + "\t" + d.get("title"));
}
以下是完全整的代码:
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopScoreDocCollector;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.RAMDirectory;
import org.apache.lucene.util.Version;

import java.io.IOException;

public class HelloLucene {
  public static void main(String[] args) throws IOException, ParseException {
    // 0. Specify the analyzer for tokenizing text.
    //    The same analyzer should be used for indexing and searching
    StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_44);

    // 1. create the index
    Directory index = new RAMDirectory();

    IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_44, analyzer);

    IndexWriter w = new IndexWriter(index, config);
    addDoc(w, "Lucene in Action", "193398817");
    addDoc(w, "Lucene for Dummies", "55320055Z");
    addDoc(w, "Managing Gigabytes", "55063554A");
    addDoc(w, "The Art of Computer Science", "9900333X");
    w.close();

    // 2. query
    String querystr = args.length > 0 ? args[0] : "lucene";

    // the "title" arg specifies the default field to use
    // when no field is explicitly specified in the query.
    Query q = new QueryParser(Version.LUCENE_44, "title", analyzer).parse(querystr);

    // 3. search
    int hitsPerPage = 10;
    IndexReader reader = DirectoryReader.open(index);
    IndexSearcher searcher = new IndexSearcher(reader);
    TopScoreDocCollector collector = TopScoreDocCollector.create(hitsPerPage, true);
    searcher.search(q, collector);
    ScoreDoc[] hits = collector.topDocs().scoreDocs;
    
    // 4. display results
    System.out.println("Found " + hits.length + " hits.");
    for(int i=0;i<hits.length;++i) {
      int docId = hits[i].doc;
      Document d = searcher.doc(docId);
      System.out.println((i + 1) + ". " + d.get("isbn") + "\t" + d.get("title"));
    }

    // reader can only be closed when there
    // is no need to access the documents any more.
    reader.close();
  }

  private static void addDoc(IndexWriter w, String title, String isbn) throws IOException {
    Document doc = new Document();
    doc.add(new TextField("title", title, Field.Store.YES));

    // use a string field for isbn because we don't want it tokenized
    doc.add(new StringField("isbn", isbn, Field.Store.YES));
    w.addDocument(doc);
  }
}
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值