package com.xuyw;
import java.io.File;
import java.io.FileReader;
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.IndexWriterConfig;
import org.apache.lucene.queryParser.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 org.apache.lucene.util.Version;
/**
* Lucene1
*
* @author xuyw
* @email xyw10000@163.com
* @date 2014-07-05
*/
public class Lucene1 {
public static final String DOCUMENT_PATH = "D:\\test\\document";
public static final String INDEX_PATH = "D:\\test\\index";
/**
* 创建索引
*
* @throws Exception
*
*/
public static void createIndex() throws Exception {
// Directory directory = new RAMDirectory();//内存中
Directory directory = FSDirectory.open(new File(INDEX_PATH));// 硬盘
IndexWriterConfig indexwriteConfig = new IndexWriterConfig(
Version.LUCENE_35, new StandardAnalyzer(Version.LUCENE_35));
IndexWriter indexWriter = new IndexWriter(directory, indexwriteConfig);
File file = new File(DOCUMENT_PATH);
for (File f : file.listFiles()) {
Document document = new Document();// 创建文档
document.add(new Field("content", new FileReader(f)));// 存储文档内容
document.add(new Field("name", f.getName(), Field.Store.YES,
Field.Index.ANALYZED_NO_NORMS));// 存储名字到索引中不分词
document.add(new Field("path", f.getAbsolutePath(),
Field.Store.YES, Field.Index.ANALYZED_NO_NORMS));// 存储路径到索引中不分词
indexWriter.addDocument(document);// 添加文档到索引
}
indexWriter.close();
}
/**
* 查找
*
* @param keyword
*/
public static void search(String keyword) throws Exception {
Directory directory = FSDirectory.open(new File(INDEX_PATH));// 硬盘
IndexReader indexReader = IndexReader.open(directory);// 打开索引
IndexSearcher indexSearch = new IndexSearcher(indexReader);// 创建IndexSearcher
QueryParser qparser = new QueryParser(Version.LUCENE_35, "content",
new StandardAnalyzer(Version.LUCENE_35));// 创建qparser
// 在content中查找
Query query = qparser.parse(keyword);// 关键字
TopDocs topdoc = indexSearch.search(query, 10);// 查找前10条
ScoreDoc[] scoredoc = topdoc.scoreDocs;// 查询的结果集
for (ScoreDoc sc : scoredoc) {
Document doc = indexSearch.doc(sc.doc);// 通过doc获取文档
System.out.println("文档名称: "
+ doc.get("name") + " 路径:" + doc.get("path"));
}
indexReader.close();
}
public static void main(String[] args) throws Exception {
//Lucene1.createIndex();
Lucene1.search("Android");
}
}