Lucene是一个基于Java的开源全文信息检索工具包。
MyTest.Java
public class MyTest {
/// 存放需要分析的文件的地址
private static String FILE_PATH = "/Users/zoujs/Desktop/test4lucene";
// 存放索引的位置
private static String INDEX_PATH = "/Users/zoujs/Desktop/index4lucene";
@Test
public void createIndex() {
IndexUtils.createIndex(INDEX_PATH, FileUtils.loadFiles(FILE_PATH));
}
@Test
public void searchIndex() {
SearcherUtils.search(INDEX_PATH, "title", "china");
}
}
FileBean.java
public class FileBean implements Serializable{
private String title;
private String content;
private int id;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public String toString() {
return "FileBean{" +
"title='" + title + '\'' +
", content='" + content + '\'' +
", id=" + id +
'}';
}
}
IndexUtils.java
public class IndexUtils {
public static void createIndex(String indexPath, List<FileBean> files) {
Directory directory = null;
try {
if (StringUtils.isBlank(indexPath))
directory = new RAMDirectory();
else
directory = FSDirectory.open(Paths.get(indexPath));
// 获取分析器
Analyzer analyzer = new StandardAnalyzer(); //标准分析器
// IndexWriter的配置
IndexWriterConfig indexWriterConfig = new IndexWriterConfig(analyzer);
indexWriterConfig.setOpenMode(IndexWriterConfig.OpenMode.CREATE); //无索引文件则创建,有则在后面继续添加
// 创建IndexWriter
IndexWriter writer = new IndexWriter(directory, indexWriterConfig);
// 遍历文件Bean创建索引
for (FileBean bean : files) {
// 创建Document
Document doc = new Document();
// 为Document创建三个字段 id title content
doc.add(new IntField("id", bean.getId(), IntField.TYPE_STORED));
doc.add(new Field("title", bean.getTitle(), TextField.TYPE_STORED));
doc.add(new TextField("content", bean.getContent(), Field.Store.YES));
// 将Document写入IndexWriter
writer.addDocument(doc);
}
// 提交
writer.commit();
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
SearchUtils.java
public class SearcherUtils {
public static void search(String indexPath, String field, String text) {
try {
// 索引文件目录
Directory directory = FSDirectory.open(Paths.get(indexPath));
// 获取IndexReader
DirectoryReader reader = DirectoryReader.open(directory);
IndexSearcher searcher = new IndexSearcher(reader);
Term term = new Term(field, text);
Query query = new TermQuery(term);
TopDocs topDocs = searcher.search(query, 10);
ScoreDoc[] hits = topDocs.scoreDocs;
if (null != hits)
for (int i = 0; i < hits.length; i++) {
Document doc = searcher.doc(hits[i].doc);
System.out.println(doc.get("title"));
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}