Lucene学习入门

来源:互联网 发布:淘宝长尾词2017 编辑:程序博客网 时间:2024/04/30 15:43

概念

建立索引

为了对文档进行索引,Lucene 提供了五个基础的类,他们分别是 Document, Field, IndexWriter, Analyzer, Directory。下面我们分别介绍一下这五个类的用途:

Document

Document 是用来描述文档的,这里的文档可以指一个 HTML 页面,一封电子邮件,或者是一个文本文件。一个 Document 对象由多个 Field 对象组成的。可以把一个 Document 对象想象成数据库中的一个记录,而每个 Field 对象就是记录的一个字段。

Field

Field 对象是用来描述一个文档的某个属性的,比如一封电子邮件的标题和内容可以用两个 Field 对象分别描述。

Analyzer

在一个文档被索引之前,首先需要对文档内容进行分词处理,这部分工作就是由 Analyzer 来做的。Analyzer 类是一个抽象类,它有多个实现。针对不同的语言和应用需要选择适合的 Analyzer。Analyzer 把分词后的内容交给 IndexWriter 来建立索引。

IndexWriter

IndexWriter 是 Lucene 用来创建索引的一个核心的类,他的作用是把一个个的 Document 对象加到索引中来。

Directory

这个类代表了 Lucene 的索引的存储的位置,这是一个抽象类,它目前有两个实现,第一个是 FSDirectory,它表示一个存储在文件系统中的索引的位置。第二个是 RAMDirectory,它表示一个存储在内存当中的索引的位置。

搜索文档

利用 Lucene 进行搜索就像建立索引一样也是非常方便的。在上面一部分中,我们已经为一个目录下的文本文档建立好了索引,现在我们就要在这个索引上进行搜索以找到包含某个关键词或短语的文档。Lucene 提供了几个基础的类来完成这个过程,它们分别是呢 IndexSearcher, Term, Query, TermQuery, Hits. 下面我们分别介绍这几个类的功能。

Query

这是一个抽象类,他有多个实现,比如 TermQuery, BooleanQuery, PrefixQuery. 这个类的目的是把用户输入的查询字符串封装成 Lucene 能够识别的 Query。

Term

Term 是搜索的基本单位,一个 Term 对象有两个 String 类型的域组成。生成一个 Term 对象可以有如下一条语句来完成:Term term = new Term(“fieldName”,”queryWord”); 其中第一个参数代表了要在文档的哪一个 Field 上进行查找,第二个参数代表了要查询的关键词。

TermQuery

TermQuery 是抽象类 Query 的一个子类,它同时也是 Lucene 支持的最为基本的一个查询类。生成一个 TermQuery 对象由如下语句完成: TermQuery termQuery = new TermQuery(new Term(“fieldName”,”queryWord”)); 它的构造函数只接受一个参数,那就是一个 Term 对象。

IndexSearcher

IndexSearcher 是用来在建立好的索引上进行搜索的。它只能以只读的方式打开一个索引,所以可以有多个 IndexSearcher 的实例在一个索引上进行操作。

Hits

Hits 是用来保存搜索的结果的。

具体实现步骤

创建索引

创建词法分析器

StandardAnalyzer analyzer = new StandardAnalyzer();

创建索引存储位置

Directory index = new RAMDirectory();

配置索引

IndexWriterConfig config = new IndexWriterConfig(analyzer);

索引写入器

IndexWriter w = new IndexWriter(index, config);

写入文档

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 tokenizeddoc.add(new StringField("isbn", isbn, Field.Store.YES));w.addDocument(doc);

关闭索引写入器

w.close();

搜索文档

创建查询

Query q = new QueryParser( "title", analyzer).parse(querystr);

读入索引

IndexReader reader = DirectoryReader.open(index);

搜索索引

TopScoreDocCollector collector = TopScoreDocCollector.create(hitsPerPage);searcher.search(q, collector);ScoreDoc[] hits = collector.topDocs().scoreDocs;

完整代码

使用版本lucene.version为5.3.1

public class LuceneTest {    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();        // 1. create the index, sotre in memory        Directory index = new RAMDirectory();        IndexWriterConfig config = new IndexWriterConfig(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 query = new QueryParser("title", analyzer).parse(querystr);        // 3. search        int hitsPerPage = 10;        IndexReader reader = DirectoryReader.open(index);        IndexSearcher searcher = new IndexSearcher(reader);        TopScoreDocCollector collector = TopScoreDocCollector.create(hitsPerPage);        searcher.search(query, 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);    }}  

输出:

Found 2 hits.1. 193398817    Lucene in Action2. 55320055Z    Lucene for Dummies  
1 0
原创粉丝点击