1. Lucence基本概念

Lucence是一个java编写的全文检索类库,使用它可以为一个应用或者站点增加检索功能。

它通过增加内容到一个全文索引来完成检索功能。然后允许你基于这个索引去查询,返回结果,结果要么根据查询的相关度来排序要么根据任意字段如文档最后修改日期来排序。

增加到Lucence的内容可以来自多种数据源,如SQL/NOSQL 数据库,文件系统,甚至从站点上。

1.1 检索与索引

Lucence能快速的完成查询结果,是因为它不是直接搜索的文本,而是搜索一个索引。这类似于通过查询书后的索引的关键字来返回一本书的页面,而不是在书中的每页来搜索这个单词。

这种类型的索引称之为 反向搜索,因为它反转了一个页核心数据结构(页—>单词)到关键字核心的数据结构(单词à页)。

1.2 文档

在lucence中,一个文件是一个搜索和索引的单元,一个索引包含一个或者多个文档。

构建索引包含增加文档到一个IndexWriter,搜索包含从通过IndexSearcher来从一个索引中检索文档。

一个Lucence文档不必一定是一个常用英语中的单词文档。例如,如果你创建一个数据库的用户表的lucence索引,那么在索引中每个用户代表一个lucence文档。

1.3 字段

一个文档包含一个或者多个字段。一个字段仅仅是一个键值对。例如,通常在应用中的title字段。在title字段中,字段名称为title,值是该title包含的内容。

在lucence中构建索引也包含创建包含一个或者多个字段的文档,并且增加这些文档到IndexWriter。

1.4 检索

检索需要在一个索引已经构建完成后。它包含创建一个查询(Query)和处理该查询到IndexSearcher中,然后返回一组Hit。

1.5 查询(Query)

Lucence拥有自己的查询语言。Lucence查询语言支持用户指定查询的字段,字段的权重,使用联合查询如AND/OR/NOT和其它功能。

2. lucence如何工作?

lucence工作原理

lucence架构如下:

2.1. 索引过程:

1) 有一系列被索引文件

2) 被索引文件经过语法分析和语言处理形成一系列词(Term)。

3) 经过索引创建形成词典和反向索引表。

4) 通过索引存储将索引写入硬盘。

简单示例:

StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_40);
Directory index = new RAMDirectory(); IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_40, 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();

其中,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);
}

2.2 搜索过程:

a) 用户输入查询语句。

b) 对查询语句经过语法分析和语言分析得到一系列词(Term)。

c) 通过语法分析得到一个查询树。

d) 通过索引存储将索引读入到内存。

e) 利用查询树搜索索引,从而得到每个词(Term)的文档链表,对文档链表进行交,差,并得到结果文档。

f) 将搜索到的结果文档对查询的相关性进行排序。

g) 返回查询结果给用户。

搜索一般三步,如下:

2.2.1 构建查询语句

示例:

String querystr = args.length > 0 ? args[0] : "lucene";
Query q = new QueryParser(Version.LUCENE_40, "title", analyzer).parse(querystr);

2.2.2 搜索前10

int hitsPerPage = 10;
IndexReader reader = IndexReader.open(index);
IndexSearcher searcher = new IndexSearcher(reader);
TopScoreDocCollector collector = TopScoreDocCollector.create(hitsPerPage, true);
searcher.search(q, collector);
ScoreDoc[] hits = collector.topDocs().scoreDocs;

2.2.3 展示结果

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"));
}

2.3 完整过程

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_40); // 1. create the index
Directory index = new RAMDirectory(); IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_40, 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_40, "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);
}
}

参考文献:

【1】http://www.lucenetutorial.com/

【2】 http://www.cnblogs.com/forfuture1978/archive/2010/06/13/1757479.html

lucence学习系列之一 基本概念的更多相关文章

  1. solr课程学习系列-solr的概念与结构(1)

    Solr是基于Lucene的采用Java5开发的一个高性能全文搜索服务器.源于lucene,却更比Lucene更为丰富更为强大的查询语言.同时实现了可配置.可扩展并对查询性能进行了优化,并且提供了一个 ...

  2. zabbix学习系列之基础概念

    触发器 概念 "监控项"仅负责收集数据,而通常收集数据的目的还包括在某指标对应的数据超出合理范围时给相关人员发送警告信息,"触发器"正式英语为监控项所收集的数据 ...

  3. IDEA学习系列之Module概念

    感谢原文作者:小manong 原文链接:https://www.jianshu.com/p/fcccc37fcb73 简单应用:IDEA Maven创建多个Module相互依赖 1.Module的概念 ...

  4. solr课程学习系列-solr服务器配置(2)

    本文是solr课程学习系列的第2个课程,对solr基础知识不是很了解的请查看solr课程学习系列-solr的概念与结构(1) 本文以windows的solr6服务器搭建为例. 一.solr的工作环境: ...

  5. http协议学习系列

    深入理解HTTP协议(转)  http://www.blogjava.net/zjusuyong/articles/304788.html http协议学习系列   1. 基础概念篇 1.1 介绍 H ...

  6. 分布式缓存技术redis学习系列(五)——redis实战(redis与spring整合,分布式锁实现)

    本文是redis学习系列的第五篇,点击下面链接可回看系列文章 <redis简介以及linux上的安装> <详细讲解redis数据结构(内存模型)以及常用命令> <redi ...

  7. 分布式缓存技术redis学习系列(四)——redis高级应用(集群搭建、集群分区原理、集群操作)

    本文是redis学习系列的第四篇,前面我们学习了redis的数据结构和一些高级特性,点击下面链接可回看 <详细讲解redis数据结构(内存模型)以及常用命令> <redis高级应用( ...

  8. React学习系列

    React学习系列 系列学习react 翻译地址 https://scotch.io/tutorials/learning-react-getting-started-and-concepts 我是初 ...

  9. Asp.Net MVC5入门学习系列②

    原文:Asp.Net MVC5入门学习系列② 添加一个Controller(控制器) 因为我们用的是Asp.Net MVC,MVC最终还是一套框架,所以我们还是需要遵循它才能玩下去,或者说是更好的利用 ...

随机推荐

  1. HBase常用命令汇总——综述(一)

    hbase(main):009:0> help HBase Shell, version 1.2.4, r67592f3d062743907f8c5ae00dbbe1ae4f69e5af, Tu ...

  2. day7 opencv+python 读取视频,没有东西

    1.读取视频man.avi, 报错. 我的视频和文件在同一目录下. #coding=utf-8 import numpy as np import cv2 cap = cv2.VideoCapture ...

  3. C#随堂

    顺序语句 上到下执行 分支语句 if    else switch() { case 1: Console.WriteLine(1); break; case 2: Console.WriteLine ...

  4. web存储机制(localStorage和sessionStorage)

    web存储包括两种:sessionStorage 和 localStorage(都是限定在文档源级别,非同源文档间无法共享) 1.sessionStorage 数据放在服务器上(IE不支持) 严格用于 ...

  5. json简单操作

    通过内置的json模块对json数据进行编码 1.对数据进行编码(dumps) import json #使用dumps将python数据结构转换为json data = { , "name ...

  6. Siki_Unity_2-2_NGUI_UI插件学习(3.6.8版本)(未学)

    Unity 2-2 NGUI UI插件学习(3.6.8版本)(未学)

  7. selenium 标签页切换

    from selenium import webdriver import time browser=webdriver.Chrome() browser.maximize_window() # 窗口 ...

  8. 十大经典排序算法总结 (Python)

    作业部落:https://www.zybuluo.com/listenviolet/note/1399285 以上链接是自己在作业部落编辑的排序算法总结- Github: https://github ...

  9. PIL包中图像的mode参数

    在这里的第一篇. 这篇的是为了说明PIL库中图像的mode参数. 我做的事情是: 在本地找了jpg的图,convert为不同mode,将不同的图截取做了个脑图,有个直观的感觉吧. 把不同mode的图通 ...

  10. 第六次ScrumMeeting博客

    第六次ScrumMeeting博客 本次会议于10月31日(二)22时整在3公寓725房间召开,持续15分钟. 与会人员:刘畅.辛德泰.窦鑫泽.张安澜.赵奕.方科栋. 除了汇报任务外,窦鑫泽同学还就前 ...