下面就介绍一下索引的建立、合并及优化操作
1.索引格式
其实索引目录有两种格式,一种是除配置文件外,每一个Document独立成为一个文件(这种搜索起来会影响速度)。另一种是全部的Document成一个文件,这样属于复合模式就快了。
2.索引文件可放的位置:
索引可以存放在两个地方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);
3.索引的合并
这个可用IndexWriter.addIndexes(Directory[] dirs)将目录加进去
来看个例子:
{
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()方法调用。
4.对索引的其它操作:
IndexReader类是用来操作索引的,它有对Document,Field的删除等操作。 删除及搜索下篇继续