Lucene
lucene 是全文检索的一种实现,是一种工具包 用于中小型应用实现对文本的全文检索,
solr 全文搜索服务器 大型应用
lucene api
增删改 IndexWriter(索引写入器)
查询 IndexSearcher(索引搜索器)
索引目录(Directory): 存储索引文件目录的抽象 ,里面放索引文件,Directory 是一个抽象类 要用他的子类FSDirectory(文件系统目录)来创建对象。
Directory directory = FSDirectory.open(Paths.get(Path));
document 的crud
增加:indexWriter.addDocument(document1);//添加到缓冲区
修改:indexWriter.updateDocument(new Term("content", "lucene"), document1);
//索引目录
Directory arg0 = FSDirectory.open(Paths.get(Path));
//对写入做配置 传入分词器
IndexWriterConfig arg1=new IndexWriterConfig(new SimpleAnalyzer());
IndexWriter indexWriter =new IndexWriter(arg0, arg1);
Document document1=new Document();
document1.add(new TextField("id", "5", Store.YES));
document1.add(new TextField("title", "doc5", Store.YES));
document1.add(new TextField("content", "doca aaa aaaaaaaaa", Store.YES));
indexWriter.updateDocument(new Term("content", "lucene"), document1);
indexWriter.commit();
indexWriter.close();
删除: indexWriter.deleteAll();//删除所有
indexWriter.deleteDocuments(new Term("content","lucence")) ; //根据单词删除 这个单词是指某个字段中是否包含某个单词 content字段中包含lucence单词与否
indexWriter.deleteDocuments(query)// 删除包含某个查询条件的
//indexWriter.deleteAll();删除所有 //indexWriter.deleteDocuments(new Term("content", "hello")); String query="hello"; String f="content"; Analyzer a=new SimpleAnalyzer(); QueryParser queryParser=new QueryParser(f, a); Query queryqq=queryParser.parse(query); indexWriter.deleteDocuments(queryqq); indexWriter.commit(); indexWriter.close();
获取:Document document=indexSearcher.doc(docId);
查询:TopDocs topDocs=indexSearcher.search(query, n);//查询top n个
Lucene倒排索引原理
这篇文章是转再载的, 转载地址:http://chinajweb.iteye.com/blog/2085870
Lucene是一个高性能的java全文检索工具包,它使用的是倒排文件索引结构。该结构及相应的生成算法如下:
0)设有两篇文章1和2
文章1的内容为:Tom lives in Guangzhou,I live in Guangzhou too.
文章2的内容为:He once lived in Shanghai.
1)由于lucene是基于关键词索引和查询的,首先我们要取得这两篇文章的关键词,通常我们需要如下处理措施
a.我们现在有的是文章内容,即一个字符串,我们先要找出字符串中的所有单词,即分词。英文单词由于用空格分隔,比较好处理。中文单词间是连在一起的需要特殊的分词处理。
b.文章中的”in”, “once” “too”等词没有什么实际意义,中文中的“的”“是”等字通常也无具体含义,这些不代表概念的词可以过滤掉
c.用户通常希望查“He”时能把含“he”,“HE”的文章也找出来,所以所有单词需要统一大小写。
d.用户通常希望查“live”时能把含“lives”,“lived”的文章也找出来,所以需要把“lives”,“lived”还原成“live”
e.文章中的标点符号通常不表示某种概念,也可以过滤掉
在lucene中以上措施由Analyzer类完成
经过上面处理后
文章1的所有关键词为:[tom] [live] [guangzhou] [i] [live] [guangzhou]
文章2的所有关键词为:[he] [live] [shanghai]
2) 有了关键词后,我们就可以建立倒排索引了。上面的对应关系是:“文章号”对“文章中所有关键词”。倒排索引把这个关系倒过来,变成:“关键词”对“拥有该关键词的所有文章号”。文章1,2经过倒排后变成
关键词 文章号
guangzhou 1
he 2
i 1
live 1,2
shanghai 2
tom 1
通常仅知道关键词在哪些文章中出现还不够,我们还需要知道关键词在文章中出现次数和出现的位置,通常有两种位置:a)字符位置,即记录该词是 文章中第几个字符(优点是关键词亮显时定位快);b)关键词位置,即记录该词是文章中第几个关键词(优点是节约索引空间、词组(phase)查询 快),lucene 中记录的就是这种位置。
加上“出现频率”和“出现位置”信息后,我们的索引结构变为:
关键词 文章号[出现频率] 出现位置
guangzhou 1[2] 3,6
he 2[1] 1
i 1[1] 4
live 1[2],2[1] 2,5,2
shanghai 2[1] 3
tom 1[1] 1
以live 这行为例我们说明一下该结构:live在文章1中出现了2次,文章2中出现了一次,它的出现位置为“2,5,2”这表示什么呢?我们需要结合文章号和出现 频率来分析,文章1中出现了2次,那么“2,5”就表示live在文章1中出现的两个位置,文章2中出现了一次,剩下的“2”就表示live是文章2中第 2个关键字。
以上就是lucene索引结构中最核心的部分。我们注意到关键字是按字符顺序排列的(lucene没有使用B树结构),因此lucene可以用二元搜索算法快速定位关键词。
实现时 lucene将上面三列分别作为词典文件(Term Dictionary)、频率文件(frequencies)、位置文件 (positions)保存。其中词典文件不仅保存有每个关键词,还保留了指向频率文件和位置文件的指针,通过指针可以找到该关键字的频率信息和位置信 息。
Lucene中使用了field的概念,用于表达信息所在位置(如标题中,文章中,url中),在建索引中,该field信息也记录在词典文件中,每个关键词都有一个field信息(因为每个关键字一定属于一个或多个field)。
为了减小索引文件的大小,Lucene对索引还使用了压缩技术。首先,对词典文件中的关键词进行了压缩,关键词压缩为<前缀长度,后 缀>,例如:当前词为“阿拉伯语”,上一个词为“阿拉伯”,那么“阿拉伯语”压缩为<3,语>。其次大量用到的是对数字的压缩,数字只 保存与上一个值的差值(这样可以减小数字的长度,进而减少保存该数字需要的字节数)。例如当前文章号是16389(不压缩要用3个字节保存),上一文章号 是16382,压缩后保存7(只用一个字节)。
下面我们可以通过对该索引的查询来解释一下为什么要建立索引。
假设要查询单词 “live”,lucene先对词典二元查找、找到该词,通过指向频率文件的指针读出所有文章号,然后返回结果。词典通常非常小,因而,整个过程的时间是毫秒级的。
而用普通的顺序匹配算法,不建索引,而是对所有文章的内容进行字符串匹配,这个过程将会相当缓慢,当文章数目很大时,时间往往是无法忍受的。
lucene 入门实例
1 引入夹包
maven pom.xml
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-core</artifactId>
<version>5.3.1</version>
</dependency>
<!--一般分词器,适用于英文分词-->
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-analyzers-common</artifactId>
<version>5.3.1</version>
</dependency>
<!--中文分词器-->
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-analyzers-smartcn</artifactId>
<version>5.3.1</version>
</dependency>
<!--对分词索引查询解析-->
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-queryparser</artifactId>
<version>5.3.1</version>
</dependency>
<!--检索关键字高亮显示-->
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-highlighter</artifactId>
<version>5.3.1</version>
</dependency>
夹包: core (核心包) analyzers(分词) queryparse (解析字符串) 这几个包相对重要
2 测试:
1测试创建索引
//索引目录
private static final String Path = "D:\\lucene";
//现在帖子的内容是写死在下面的 以后从数据库中读取
static String doc1="hello word";
static String doc2="hello java word";
static String doc3="hello lucene word";
/*创建索引:
* 1 创建IndexWrite
* 2 把要创建索引的文本数据放入Document的字段中
* 3 通过indexWriter吧document写入
*/
/* 创建索引
public static void main(String[] args) {
try {
// 1 创建IndexWrite
//索引目录
Directory arg0 = FSDirectory.open(Paths.get(Path));
//对写入做配置 传入分词器
IndexWriterConfig arg1=new IndexWriterConfig(new SimpleAnalyzer());
IndexWriter indexWriter =new IndexWriter(arg0, arg1);
System.out.println(indexWriter);
//2 把要创建索引的文本数据放入Document的字段中
Document document1=new Document();
document1.add(new TextField("id", "1", Store.YES));
document1.add(new TextField("title", "doc1", Store.YES));
document1.add(new TextField("content", doc1, Store.YES));
Document document2=new Document();
document2.add(new TextField("id", "2", Store.YES));
document2.add(new TextField("title", "doc2", Store.YES));
document2.add(new TextField("content", doc2, Store.YES));
Document document3=new Document();
document3.add(new TextField("id", "3", Store.YES));
document3.add(new TextField("title", "doc3", Store.YES));
document3.add(new TextField("content", doc3, Store.YES));
// 3 通过indexWriter吧document写入
indexWriter.addDocument(document1);//添加到缓冲区
indexWriter.addDocument(document2);
indexWriter.addDocument(document3);
indexWriter.commit();//
indexWriter.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
2测试搜索索引
/*
* 搜索索引:
* 1 创建IndexSearch
* 2 创建Query对象
* 3 使用IndexSearch对象传入Query 进行搜索
* 4 从结果中获取documentId 再通过他获取document
* 5 把document转换成我们想要的东西进行返回
*/
//索引目录
private static final String Path = "D:\\lucene";
public static void main(String[] args) throws Exception {
// 1 创建IndexSearch
//索引目录
Directory directory = FSDirectory.open(Paths.get(Path));
IndexReader r =DirectoryReader.open(directory);//索引读入器
IndexSearcher indexSearcher=new IndexSearcher(r );//索引搜索器
//2 创建Query对象 把特定字符串解析得到
String paseStr="content:hello";
//用它对搜索条件进行分词
Analyzer a=new SimpleAnalyzer();
String defaultField="content";//如果搜索字符串中没有设定 就使用默认的
QueryParser paser=new QueryParser(defaultField, a);
Query query=paser.parse(paseStr);
//3 使用IndexSearch对象传入Query 进行搜索
int n=1000;
TopDocs topDocs=indexSearcher.search(query, n);//查询top n个
System.out.println("总命中数"+topDocs.totalHits);
//4 从结果中获取documentId 再通过他获取document
ScoreDoc[] scoreDocs=topDocs.scoreDocs;//命中纪录数据
for(ScoreDoc scoreDoc:scoreDocs){
int docId =scoreDoc.doc;//获取文档编号
//5 把document转换成我们想要的东西进行返回
Document document=indexSearcher.doc(docId);
System.out.println("id=="+document.get("id"));
System.out.println("title=="+document.get("title"));
System.out.println("content=="+document.get("content"));
}
}
写一个创建索引和搜索索引的工具类
package com.myshop.util.web;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.core.SimpleAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field.Store;
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.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import com.myshop.bean.LuceneResult;
public class LuceneUtils {
//创建索引
public static void CreateLuceneIndex(String[] str,String path){
/*1 创建IndexWrite
*2 把要创建索引的文本数据放入Document的字段中
*3 通过indexWriter吧document写入
*/
try {
IndexWriterConfig conf=new IndexWriterConfig(new SimpleAnalyzer());
Directory d= FSDirectory.open(Paths.get(path));
IndexWriter indexWriter=new IndexWriter(d, conf);
for(int i=1;i<=str.length;i++){
Document doc=new Document(); //必须放在里面 每次创建一个文档
doc.add(new TextField("id", String.valueOf(i), Store.YES));
doc.add(new TextField("title", "doc"+i, Store.YES));
doc.add(new TextField("content", str[i-1], Store.YES));
indexWriter.addDocument(doc);
}
indexWriter.commit();
indexWriter.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/*搜索索引:
* 1 创建IndexSearch
* 2 创建Query对象
* 3 使用IndexSearch对象传入Query 进行搜索
* 4 从结果中获取documentId 再通过他获取document
* 5 把document转换成我们想要的东西进行返回
*/
public static List<LuceneResult> selectIndex(String queryStr,String path){
List<LuceneResult> list=new ArrayList<>();
try {
Directory directory;
directory = FSDirectory.open(Paths.get(path));
IndexReader r=DirectoryReader.open(directory);
IndexSearcher indexSearcher=new IndexSearcher(r);
String defaultS="content";
Analyzer a=new SimpleAnalyzer();
QueryParser queryParser=new QueryParser(defaultS, a);
Query query=queryParser.parse(queryStr);
TopDocs topDocs=indexSearcher.search(query, 1000000);
System.out.println(topDocs.totalHits+"总命中数");
ScoreDoc[] scoreDocs=topDocs.scoreDocs;
for(ScoreDoc scoreDoc:scoreDocs){
LuceneResult luceneResult=new LuceneResult();
int docId=scoreDoc.doc;
System.out.println(docId);
Document document=indexSearcher.doc(docId);
String id=document.get("id");
System.out.println(id);
String content=document.get("content");
String title=document.get("title");
luceneResult.setContent(content);
luceneResult.setTitle(title);;
luceneResult.setId(id);
list.add(luceneResult);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
}