項目應用場景
最近需要做一個簡單的信息展示系統,信息和普通新聞差不多,主要有標題和內容,信息需要能通過關鍵詞檢索到,考慮到信息比較簡單,檢索也很簡單,主要是通過標題和內容搜索,不想用Solr搭建搜索引擎,想用的Lucene寫個簡的搜索,能構增加索引、刪除索引,通過關鍵字搜索信息就可以了。
項目依賴包
Lucene使用最新版本5.3.1 Maven配置如下
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-core</artifactId>
<version>5.3.1</version>
</dependency>
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-queryparser</artifactId>
<version>5.3.1</version>
</dependency>
分詞器選擇
由於項目對搜索精度沒有太高要求,所以選擇常用的IK分詞器就可以了,選用的版本爲IKAnalyzer2012_V5.jar ,百度可以很好搜索
文章準備
在C:/MyIndex/doc 目錄下準備了兩篇測試新聞,如下圖所示
創建索引
public static void indexFile() throws IOException {
Directory dir = FSDirectory.open(Paths.get("C:/MyIndex"));
Analyzer analyzer = new IKAnalyzer();
IndexWriterConfig iwc = new IndexWriterConfig(analyzer);
IndexWriter writer = new IndexWriter(dir, iwc);
File path=new File("C:\\MyIndex\\doc");
File [] file= path.listFiles();
for(File f:file){
String tile=f.getName();
String content="";
BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream(f),"utf-8"));
String line="";
while (null!=(line=br.readLine())) {
content+=line;
}
Document doc = new Document();
doc.add(new TextField("name", tile, Field.Store.YES));
doc.add(new TextField("content", content,Field.Store.YES));
writer.addDocument(doc);
System.out.println("add " + tile);
}
writer.close();
}
測試搜索
public static void search() throws IOException, ParseException {
Analyzer analyzer = new IKAnalyzer();
IndexReader reader = DirectoryReader.open(FSDirectory.open(Paths.get("C:/MyIndex")));
IndexSearcher searcher = new IndexSearcher(reader);
QueryParser parser = new QueryParser("name", analyzer);
String queries = "奧巴馬";
Query query = parser.parse(queries);
System.out.println("Searching for: " + query.toString(queries));
TopDocs results = searcher.search(query, 10);
System.out.println("Total match:" + results.totalHits);
ScoreDoc[] hits = results.scoreDocs;
int count = 1;
for (ScoreDoc hit : hits) {
Document doc1 = searcher.doc(hit.doc);
String res = doc1.get("name");
System.err.println(count + " " + res + ", " + hit.score);
count++;
}
}
運行結果
add 習近平會見奧巴馬: 中美兩國要牢牢把握構建新型大國關係正確方向.txt
add 最高法緊急下令暫緩運毒7.5公斤農民死刑執行.txt
Searching for: name:奧 name:巴馬
Total match:1
1 習近平會見奧巴馬: 中美兩國要牢牢把握構建新型大國關係正確方向.txt, 0.30935922