import java.io.File;
import java.io.IOException;
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.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.IndexWriterConfig.OpenMode;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.LockObtainFailedException;
import org.apache.lucene.util.Version;
public class LuceneTest {
String docsPath = null; //文件位置
String indexPath =null; //索引位置
public static void main(String[] args) {
LuceneTest test = new LuceneTest();
try {
test.index();
} catch (CorruptIndexException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (LockObtainFailedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 先创立索引
* @throws IOException
* @throws LockObtainFailedException
* @throws CorruptIndexException
*/
public void index() throws CorruptIndexException, LockObtainFailedException, IOException
{
docsPath="F:\\Search engine\\搜索引擎\\lucene-3.1.0-src\\lucene-3.1.0\\contrib\\analyzers\\common\\readm.txt";
indexPath="D:\\mywork\\LuceneTest\\lucenedic";
if(docsPath==null)
{
System.err.println("docsPath为空");
System.exit(1);
}
File docDir = new File(docsPath);
Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_31);
Directory dir = FSDirectory.open(new File(indexPath));
IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_31, analyzer);
/*IndexWriter indexWriter1 = new IndexWriter(dir,new IndexWriterConfig(Version.LUCENE_31,
new WhitespaceAnalyzer(Version.LUCENE_31)));*/
iwc.setOpenMode(OpenMode.CREATE_OR_APPEND);
IndexWriter indexWriter = new IndexWriter(dir,iwc);
Document doc = new Document();
Field pathField = new Field("path",docDir.getPath(),Field.Store.YES,Field.Index.NOT_ANALYZED_NO_NORMS);
pathField.setOmitTermFreqAndPositions(true);
doc.add(pathField);
indexWriter.addDocument(doc);
indexWriter.close();
}
}
lucene如何创建一个索引
最新推荐文章于 2025-04-11 14:37:53 发布