索引文件可放的位置:
索引可以存放在两个地方1.硬盘,2.内存放在硬盘上可以用FSDirectory(),放在内存的用RAMDirectory()不过一关机就没了。
FSDirectory.getDirectory(File file, boolean create)
FSDirectory.getDirectory(String path, boolean create)
两个工厂方法返回目录New RAMDirectory()就直接可以再和
IndexWriter(Directory d, Analyzer a, boolean create)
一配合就行了,例如:
IndexWrtier indexWriter = new IndexWriter(FSDirectory.getDirectory(“c:\\index”, true ), new StandardAnlyazer(), true );
IndexWrtier indexWriter = new IndexWriter( new RAMDirectory(), new StandardAnlyazer(), true );
索引的合并
这个可用这个将目录加进去
IndexWriter.addIndexes(Directory[] dirs)
来看个例子:
public void UniteIndex() throws IOException
{
IndexWriter writerDisk = new IndexWriter(FSDirectory.getDirectory( " c:\\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( " c:\\indexDisk " );
Hits hits = indexSearcher.search(query);
System.out.println( " 找到了 " + hits.length() + " 结果 " );
for ( int i = 0 ;i
{
Document doc = hits.doc(i);
System.out.println(doc.get( " name " ));
}
}
这个例子是将内存中的索引合并到硬盘上来.
注意:合并的时候一定要将被合并的那一方的IndexWriter的close()方法调用。
对索引的其它操作:
IndexReader类是用来操作索引的,它有对Document,Field的删除等操作。
下面一部分的内容是:全文的搜索
全文的搜索主要是用:IndexSearcher,Query,Hits,Document(都是Query的子类),有的时候用QueryParser
主要步骤:
1 . new QueryParser(Field字段, new 分析器)
2 .Query query = QueryParser.parser(“要查询的字串”);这个地方我们可以用反射api看一下query究竟是什么类型
3 . new IndexSearcher(索引目录).search(query);返回Hits
4 .用Hits.doc(n);可以遍历出Document
5 .用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( " c:\\indexDisk " );
Hits hits = indexSearcher.search(query);
不管是什么类型,无非返回的就是Query的子类,我们完全可以不用这两步直接new个Query的子类的实例就ok了,不过一般还是用这两步因为它返回的是PhraseQuery这个是非常强大的query子类它可以进行多字搜索用QueryParser可以设置各个关键字之间的关系这个是最常用的了。
IndexSearcher:
其实IndexSearcher它内部自带了一个IndexReader用来读取索引的,IndexSearcher有个close()方法,这个方法不是用来关闭IndexSearche的是用来关闭自带的IndexReader。
QueryParser呢可以用parser.setOperator()来设置各个关键字之间的关系(与还是或)它可以自动通过空格从字串里面将关键字分离出来。
注意:用QueryParser搜索的时候分析器一定的和建立索引时候用的分析器是一样的。
Query:
可以看一个lucene2.0的帮助文档有很多的子类:
BooleanQuery, ConstantScoreQuery, ConstantScoreRangeQuery, DisjunctionMaxQuery,FilteredQuery, MatchAllDocsQuery, MultiPhraseQuery, MultiTermQuery,PhraseQuery, PrefixQuery, RangeQuery, SpanQuery, TermQuery
各自有用法看一下文档就能知道它们的用法了
下面一部分讲一下lucene的分析器:
分析器是由分词器和过滤器组成的,拿英文来说吧分词器就是通过空格把单词分开,过滤器就是把the,to,of等词去掉不被搜索和索引。
我们最常用的是StandardAnalyzer()它是lucene的标准分析器它集成了内部的许多的分析器。
最后一部分了:lucene的高级搜索了
1.排序
Lucene有内置的排序用IndexSearcher.search(query,sort)但是功能并不理想。我们需要自己实现自定义的排序。
这样的话得实现两个接口: ScoreDocComparator, SortComparatorSource
用IndexSearcher.search(query,newSort(new SortField(String Field,SortComparatorSource)));
就看个例子吧:
这是一个建立索引的例子:
public void IndexSort() throws IOException
{
IndexWriter writer = new IndexWriter( " C:\\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("C:\\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("C:\\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
{
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
{
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]
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
{
if(fieldname.equals("sort"))
return new MyScoreDocComparator("sort",reader,fieldname);
return null;
}
}
SearchSort1()输出的结果没有排序,SearchSort2()就排序了。
2.多域搜索MultiFieldQueryParser
如果想输入关键字而不想关心是在哪个Field里的就可以用MultiFieldQueryParser了,用它的构造函数即可后面的和一个Field一样。
MultiFieldQueryParser. parse(String[] queries, String[] fields, BooleanClause.Occur[] flags, Analyzer analyzer)
第三个参数比较特殊这里也是与以前lucene1.4.3不一样的地方。看一个例子就知道了
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);
1、lucene的索引不能太大,要不然效率会很低。大于1G的时候就必须考虑分布索引的问题
2、不建议用多线程来建索引,产生的互锁问题很麻烦。经常发现索引被lock,无法重新建立的情况
3、中文分词是个大问题,目前免费的分词效果都很差。如果有能力还是自己实现一个分词模块,用最短路径的切分方法,网上有教材和demo源码,可以参考。
4、建增量索引的时候很耗cpu,在访问量大的时候会导致cpu的idle为0
5、默认的评分机制不太合理,需要根据自己的业务定制
整体来说lucene要用好不容易,必须在上述方面扩充他的功能,才能作为一个商用的搜索引擎