序言
总得来说用Lucene(实验使用lucene5.1.0 )来进行建立 和搜索和操作数据库是差不多的(有点像),Document可以看作是 数据库的一行记录,Field可以看作是数据库的字段。
Lucene 其实很简单的,它最主要就是做两件事:建立索引和进行搜索
lucene的一些术语
- IndexWriter: lucene中最重要的的类之一,它主要是用来将文档加入索引,同时控制索引过程中的一些参数使用。
- Analyzer: 分析器,主要用于分析搜索引擎遇到的各种文本。常用的有StandardAnalyzer分析器,StopAnalyzer分析器,WhitespaceAnalyzer分析器等;
- Directory: 索引存放的位置;lucene提供了两种索引存放的位置,一种是磁盘,一种是内存。一般情况将索引放在磁盘上;相应地lucene提供了FSDirectory和RAMDirectory两个类;
- Document: 文档;Document相当于一个要进行索引的单元,任何可以想要被索引的文件都必须转化为Document对象才能进行索引;
- Field:字段;
- IndexSearcher: 是lucene中最基本的检索工具,所有的检索都会用到IndexSearcher工具;
- Query查询:lucene中支持模糊查询,语义查询,短语查询,组合查询等等,如有TermQuery,BooleanQuery,RangeQuery,WildcardQuery等一些类。
- QueryParser: 是一个解析用户输入的工具,可以通过扫描用户输入的字符串,生成Query对象。
- Hits: 在搜索完成之后,需要把搜索结果返回并显示给用户,只有这样才算是完成搜索的目的。在lucene中,搜索的结果的集合是用Hits类的实例来表示的。
索引步骤
参见下面:一、从Hello World开始
搜索步骤
参见下面:二、
下面拿几个例子说明:
一、从Hello World开始
- 首先建立两个文件夹
- Index文件夹:存放索引
- Docs文件夹:存放document文件
主要步骤参考
建立一个Analyzer
建立索引(IndexWriter)
加入Document
package cslab.lucene;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.Hits;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.store.FSDirectory;
public class FSDirectoryTest {
// 建立索引的路径(E:\index\)
public static final String path = "E:\\index\\";
public static void main(String[] args) throws Exception {
IndexWriter writer = new IndexWriter(FSDirectory.getDirectory(path, true), new StandardAnalyzer(), true );
Document doc1 = new Document();
doc1.add( new Field( "name" , "lighter javaeye com" ,Field.Store.YES,Field.Index.TOKENIZED));
Document doc2 = new Document();
doc2.add(new Field( "name" , " lighter blog",Field.Store.YES,Field.Index.TOKENIZED));
writer.setMaxFieldLength(3);
writer.addDocument(doc1);
writer.setMaxFieldLength(3);
writer.addDocument(doc2);
writer.close();
IndexSearcher searcher = new IndexSearcher(path);
Hits hits = null ;
Query query = null ;
QueryParser qp = new QueryParser( "name" , new StandardAnalyzer());
query = qp.parse( "lighter" );
hits = searcher.search(query);
System.out.println("查找\"lighter\"共 " + hits.length() + " 个结果 " );
query = qp.parse( "javaeye" );
hits = searcher.search(query);
System.out.println(" 查找\"javaeye\"共 " + hits.length() + " 个结果 " );
}
}
Output:
查找"lighter"共 2 个结果
查找"javaeye"共 1 个结果
二、StandardAnalyzer测试例子
StandardAnalyzer是lucene中内置的”标准分析器”,可以做如下功能:
对原有句子按照空格进行了分词
所有的大写字母都可以能转换为小写的字母
可以去掉一些没有用处的单词,例如”is”,”the”,”are”等单词,也删除了所有的标点 ,
package cslab.lucene;
import java.io.IOException;
import java.io.StringReader;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.Token;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
public class StandardAnalyzerTest {
// 构造函数
public StandardAnalyzerTest() {
}
public static void main(String[] args) {
// 生成一个StandardAnalyzer对象
Analyzer aAnalyzer = new StandardAnalyzer();
// 测试字符串
StringReader sr = new StringReader("lighter javaeye com is the are on");
// 生成TokenStream对象
TokenStream ts = aAnalyzer.tokenStream("name", sr);
try {
int i = 0;
Token t = ts.next();
while (t != null) {
// 辅助输出时显示行号
i++;
// 输出处理后的字符
System.out.println("第 " + i + " 行:" + t.termText());
// 取得下一个字符
t = ts.next();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Output:
第1行:lighter
第2行:javaeye
第3行:com
三、Lucene索引
索引格式
一种是除配置文件外,每一个Document独立成为一个文件(这种搜索起来会影响速度)。
另一种是全部的Document成一个文件,这样属于复合模式就快了。
存储位置
- 内存RAMDirectory
IndexWrtier indexWriter = new IndexWriter( new RAMDirectory(), new StandardAnlyazer(),true );
- 文件FSDirectory
IndexWrtier indexWriter = new IndexWriter(FSDirectory.getDirectory(“E:\\index, true),new StandardAnlyazer(), true );
索引的合并
IndexWriter.addIndexes(Directory[] dirs)
下面代码是把内存中的索引合并到硬盘上来
package cslab.lucene;
import java.io.IOException;
import java.io.StringReader;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.Token;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.Hits;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.RAMDirectory;
public class IndexMerge {
public void UniteIndex() throws IOException {
IndexWriter writerDisk = new IndexWriter(FSDirectory.getDirectory("E:\\indexDisk", true), new StandardAnalyzer(), true);
Document docDisk = new Document();
docDisk.add(new Field("name", "程序员之家", Field.Store.YES, Field.Index.TOKENIZED));
writerDisk.addDocument(docDisk);
RAMDirectory ramDir = new RAMDirectory();
IndexWriter writerRam = new IndexWriter(ramDir, new StandardAnalyzer(), true);
Document docRam = new Document();
docRam.add(new Field("name", "程序员杂志", Field.Store.YES,Field.Index.TOKENIZED));
writerRam.addDocument(docRam);
writerRam.close();// 这个方法非常重要,是必须调用的
writerDisk.addIndexes(new Directory[] { ramDir });
writerDisk.close();
}
public void UniteSearch() throws ParseException, IOException {
QueryParser queryParser = new QueryParser( "name" , new StandardAnalyzer());
Query query = queryParser.parse( "程序员" );
IndexSearcher indexSearcher = new IndexSearcher( "E:\\indexDisk" );
Hits hits = indexSearcher.search(query);
System.out.println("找到了" + hits.length() + "结果" );
for ( int i = 0 ;i < hits.length(); i++) {
Document doc = hits.doc(i);
System.out.println(doc.get("name"));
}
}
}
注意:合并的时候一定要将被合并的那一方的IndexWriter的close()方法调用。
索引的其他操作
IndexReader类是用来操作索引的,它有对Document, Field的删除等操作。
四、Lucene检索
全文的搜索主要是用:IndexSearcher,Query,Hits,Document(都是Query的子类),有的时候用QueryParser
主要步骤:
new QueryParser(Field字段, new 分析器)
Query query = QueryParser.parser(“要查询的字串”);这个地方我们可以用反射api看一下query究竟是什么类型
new IndexSearcher(索引目录).search(query);返回Hits
用Hits.doc(n);可以遍历出Document
用Document可得到Field的具体信息了。
其实1 ,2两步就是为了弄出个Query 实例,究竟是什么类型的看分析器了。
拿以前的例子来说吧
QueryParser queryParser = new QueryParser( "name" , new StandardAnalyzer());
Query query = queryParser.parse( "程序员" );// 这里返回的就是org.apache.lucene.search.PhraseQuery
IndexSearcher indexSearcher = new IndexSearcher( "E:\\indexDisk" );
Hits hits = indexSearcher.search(query);
不管是什么类型,无非返回的就是Query的子类,我们完全可以不用这两步直接new个Query的子类的实例就ok了,不过一般还是用这两步因为它返回的是PhraseQuery这个是非常强大的query子类它可以进行多字搜索用QueryParser可以设置各个关键字之间的关系这个是最常用的了。
五、IndexSearcher:
其实IndexSearcher它内部自带了一个IndexReader用来读取索引的,IndexSearcher有个close()方法,这个方法不是用来关闭IndexSearche的是用来关闭自带的IndexReader。
六、QueryParser
可以用parser.setOperator()来设置各个关键字之间的关系(与还是或)它可以自动通过空格从字串里面将关键字分离出来。
注意:用QueryParser搜索的时候分析器一定的和建立索引时候用的分析器是一样的。
七、Lucene高级搜索
排序
Lucene有内置的排序用 IndexSearcher.search(query, sort) 但是功能并不理想。我们需要自己实现自定义的排序。
这样的话得实现两个接口: ScoreDocComparator, SortComparatorSource
- 用IndexSearcher.search(query,newSort(new SortField(String Field,SortComparatorSource)));
package cslab.lucene;
import java.io.IOException;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.Hits;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.RangeQuery;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.ScoreDocComparator;
import org.apache.lucene.search.Sort;
import org.apache.lucene.search.SortComparatorSource;
import org.apache.lucene.search.SortField;
public class SearchSortSample {
// 建立 索引
public void IndexSort() throws IOException {
IndexWriter writer = new IndexWriter("E:\\indexStore",
new StandardAnalyzer(), true);
Document doc = new Document();
doc.add(new Field("sort", "1", Field.Store.YES, Field.Index.TOKENIZED));
writer.addDocument(doc);
doc = new Document();
doc.add(new Field("sort", "4", Field.Store.YES, Field.Index.TOKENIZED));
writer.addDocument(doc);
doc = new Document();
doc.add(new Field("sort", "3", Field.Store.YES, Field.Index.TOKENIZED));
writer.addDocument(doc);
doc = new Document();
doc.add(new Field("sort", "5", Field.Store.YES, Field.Index.TOKENIZED));
writer.addDocument(doc);
doc = new Document();
doc.add(new Field("sort", "9", Field.Store.YES, Field.Index.TOKENIZED));
writer.addDocument(doc);
doc = new Document();
doc.add(new Field("sort", "6", Field.Store.YES, Field.Index.TOKENIZED));
writer.addDocument(doc);
doc = new Document();
doc.add(new Field("sort", "7", Field.Store.YES, Field.Index.TOKENIZED));
writer.addDocument(doc);
writer.close();
}
//输出没有排序的
public void SearchSort1() throws IOException, ParseException {
IndexSearcher indexSearcher = new IndexSearcher("E:\\indexStore");
QueryParser queryParser = new QueryParser("sort",
new StandardAnalyzer());
Query query = queryParser.parse("4");
Hits hits = indexSearcher.search(query);
System.out.println("有" + hits.length() + "个结果");
Document doc = hits.doc(0);
System.out.println(doc.get("sort"));
}
//排序
public void SearchSort2() throws IOException, ParseException {
IndexSearcher indexSearcher = new IndexSearcher("E:\\indexStore");
Query query = new RangeQuery(new Term("sort", "1"), new Term("sort",
"9"), true);// 这个地方前面没有提到,它是用于范围的Query可以看一下帮助文档.
Hits hits = indexSearcher.search(query, new Sort(new SortField("sort",
new MySortComparatorSource())));
System.out.println("有" + hits.length() + "个结果");
for (int i = 0; i < hits.length(); i++) {
Document doc = hits.doc(i);
System.out.println(doc.get("sort"));
}
}
public class MyScoreDocComparator implements ScoreDocComparator {
private Integer[] sort;
public MyScoreDocComparator(String s, IndexReader reader,
String fieldname) throws IOException {
sort = new Integer[reader.maxDoc()];
for (int i = 0; i < sort.length; i++) {
Document doc = reader.document(i);
sort[i] = new Integer(doc.get("sort"));
}
}
public int compare(ScoreDoc i, ScoreDoc j) {
if (sort[i.doc] > sort[j.doc])
return 1;
if (sort[i.doc] < sort[j.doc])
return -1;
return 0;
}
public int sortType() {
return SortField.INT;
}
public Comparable sortValue(ScoreDoc i) {
// TODO 自动生成方法存根
return new Integer(sort[i.doc]);
}
}
public class MySortComparatorSource implements SortComparatorSource {
private static final long serialVersionUID = -9189690812107968361L;
public ScoreDocComparator newComparator(IndexReader reader,
String fieldname) throws IOException {
// TODO Auto-generated method stub
if (fieldname.equals("sort"))
return new MyScoreDocComparator("sort", reader, fieldname);
return null;
}
}
public static void main(String[] args) throws IOException, ParseException {
// TODO Auto-generated method stub
SearchSortSample sss = new SearchSortSample();
sss.IndexSort();
sss.SearchSort1();
sss.SearchSort2();
}
}
多域搜索MultiFieldQueryParser
如果想输入关键字而不想关心是在哪个Field里的就可以用MultiFieldQueryParser了
用它的构造函数即可后面的和一个Field一样。
MultiFieldQueryParser. parse(String[] queries, String[] fields, BooleanClause.Occur[] flags, Analyzeranalyzer)
String[] fields = {"filename", "contents", "description"};
BooleanClause.Occur[] flags = {BooleanClause.Occur.SHOULD,
BooleanClause.Occur.MUST, //在这个Field里必须出现的
BooleanClause.Occur.MUST_NOT};//在这个Field里不能出现
MultiFieldQueryParser.parse("query", fields, flags, analyzer);
八、Lucene在实际中的运用
在E:\docs\下建立三个txt文档:1.xml, 2.xml, 3.xml
其中1.txt里内容如下
<?xml version="1.0" encoding="UTF-8"?>
<samples>
<search_results>
<query id="7011">Vera Pavlova</query>
<engine id="FW14-e001" name="arXiv.org" timestamp="2014-04-11 23:11:50" status="OK"/>
<snippets/>
</search_results>
</samples>
2.xml 3.xml随便写点啥
package cslab.lucene;
import java.io.*;
import java.util.Date;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexWriter;
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.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.LockObtainFailedException;
import org.apache.lucene.store.RAMDirectory;
public class luceneTest {
public static String FileReaderAll(String FileName) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(FileName));
String line = new String();
String temp = new String();
while ((line = reader.readLine()) != null) {
temp += line;
}
reader.close();
return temp;
}
public static void main0() throws CorruptIndexException, LockObtainFailedException, IOException {
File fileDir = new File("E:\\docs\\");
File indexDir = new File("E:\\index\\");
Analyzer analyzer = new StandardAnalyzer();
IndexWriter indexWriter = new IndexWriter(indexDir, analyzer, true );
File[] textFiles = fileDir.listFiles();
long startTime = new Date().getTime();
// 增加document到索引去
for ( int i = 0 ; i < textFiles.length; i ++ ) {
System.out.println();
if (textFiles[i].isFile() && textFiles[i].getName().endsWith( ".xml" )) {
System.out.println("File" + textFiles[i].getCanonicalPath() + "正在被索引.");
String temp = FileReaderAll(textFiles[i].getCanonicalPath());
System.out.println(temp);
Document document = new Document();
Field FieldPath = new Field( "path", textFiles[i].getPath(), Field.Store.YES, Field.Index.NO);
Field FieldBody = new Field( "body", temp, Field.Store.YES, Field.Index.TOKENIZED, Field.TermVector.WITH_POSITIONS_OFFSETS);
document.add(FieldPath);
document.add(FieldBody);
indexWriter.addDocument(document);
}
}
// optimize()方法是对索引进行优化
indexWriter.optimize();
indexWriter.close();
// 测试一下索引的时间
long endTime = new Date().getTime();
System.out.println("这花费了"
+ (endTime - startTime)
+ "毫秒来把文档增加到索引里面去!"
+ fileDir.getPath());
}
public static void main1() {
Hits hits = null ;
String queryString = "</samples>";
Query query = null ;
IndexSearcher searcher = new IndexSearcher("E:\\index\\");
Analyzer analyzer = new StandardAnalyzer();
try {
QueryParser qp = new QueryParser( "body", analyzer);
query = qp.parse(queryString);
} catch (ParseException e){}
if (searcher != null ) {
hits = searcher.search(query);
if (hits.length() > 0 ) {
System.out.println(" 找到: " + hits.length() + " 个结果! " );
}
else {
System.out.println("0");
}
}
else {
System.out.println("search is null");
}
}
public static void main(String[] args) throws IOException, ParseException {
main0();
main1();
/*
Analyzer analyzer = new StandardAnalyzer();
// Store the index in memory:
//Directory directory = new RAMDirectory();
// To store an index on disk, use this instead:
Directory directory = FSDirectory.getDirectory("/tmp/testindex");
//Directory directory = FSDirectory.open("/tmp/testindex");
//Analyzer config = new IndexWriterConfig(analyzer);
IndexWriter iwriter = new IndexWriter(directory, analyzer, true);
Document doc = new Document();
String text = "This is the text to be indexed.";
doc.add(new Field("fieldname", text, Field.Store.YES, Field.Index.TOKENIZED));
iwriter.addDocument(doc);
iwriter.close();
// Now search the index:
DirectoryReader ireader = DirectoryReader.open(directory);
IndexSearcher isearcher = new IndexSearcher(ireader);
// Parse a simple query that searches for "text":
QueryParser parser = new QueryParser("fieldname", analyzer);
Query query = parser.parse("text");
ScoreDoc[] hits = isearcher.search(query, null, 1000).scoreDocs;
//assertEquals(1, hits.length);
// Iterate through the results:
for (int i = 0; i < hits.length; i++) {
Document hitDoc = isearcher.doc(hits[i].doc);
//assertEquals("This is the text to be indexed.", hitDoc.get("fieldname"));
}
ireader.close();
directory.close();
*/
}
}
九、注意点
lucene的索引不能太大,要不然效率会很低。大于1G的时候就必须考虑分布索引的问题
不建议用多线程来建索引,产生的互锁问题很麻烦。经常发现索引被lock,无法重新建立的情况
中文分词是个大问题,目前免费的分词效果都很差。如果有能力还是自己实现一个分词模块,用最短路径的切分方法,网上有教材和demo源码,可以参考。
建增量索引的时候很耗cpu,在访问量大的时候会导致cpu的idle为0
默认的评分机制不太合理,需要根据自己的业务定制