lucene入門

http://ryxxlong.javaeye.com/blog/760792,一篇很好的lucene入門程序,以下是主要代碼,包含HelloWorld.java文件,File2DocumentUtils.java文件,並在src目錄下新建luceneDataSource和luceneIndex目錄,luceneDataSource目錄放需要被搜索的文件,luceneIndex目錄是索引目錄,用到的jar包有junit-4.8.2.jar,lucene-core-3.0.2.jar,然後用JUnit運行HelloWorld.java中的search()測試方法。有不明白的地方可以參考原文:http://ryxxlong.javaeye.com/blog/760792

 

 

HelloWorld.java文件:

 

package com.reiyen.lucene.helloworld;
import java.io.File;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriter.MaxFieldLength;
import org.apache.lucene.queryParser.MultiFieldQueryParser;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.Filter;
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.FSDirectory;
import org.apache.lucene.util.Version;
import org.junit.Test;

import com.reiyen.lucene.utils.File2DocumentUtils;

public class HelloWorld {

String[] filePath = {"luceneDatasource//test addDocument test.txt",
"luceneDatasource//IndexWriter addDocument's a javadoc .txt",
"luceneDatasource//Test.html"}; //.// IndexWriter addDocument's a javadoc .txt IndexWriter.txt

String indexPath2 = ".//luceneIndex";

//使用lucene標準的分詞器
Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_30);
// Analyzer analyzer = new KeywordAnalyzer();
// PerFieldAnalyzerWrapper pfaw = new PerFieldAnalyzerWrapper(analyzer);

File indexPath = new File(indexPath2);
/**
* 創建索引
*
* IndexWriter 是用來操作(增、刪、改)索引庫的
*/
@Test
public void createIndex() throws Exception {
// file --> doc
Document[] docs = File2DocumentUtils.file2Document(filePath);

// 建立索引
// 我們注意到類 IndexWriter 的構造函數中傳入的四個參數,第一個參數指定了所創建的索引要存放的位置,他可以是一個 File
// 對象,也可以是一個 FSDirectory 對象或者 RAMDirectory 對象。
// 第二個參數指定了 Analyzer 類的一個實現,也就是指定這個索引是用哪個分詞器對文擋內容進行分詞。
// 第三個參數是一個布爾型的變量,如果爲 true 的話就代表創建一個新的索引,爲 false 的話就代表在原來索引的基礎上進行操作。
// 第四個參數是一個IndexWriter.MaxFieldLength,表示Field(字段)中的term/token(令牌)的數目,它有UNLIMITED(它的值爲2147483647,表示沒有限制),LIMITED(值爲10000)兩個已定義的值,
//也可new一個新對象,如:new IndexWriter.MaxFieldLength(2000),表示最大數目是2000個
IndexWriter indexWriter = new IndexWriter(FSDirectory.open(indexPath), analyzer, true,
MaxFieldLength.LIMITED);
//最後把document用 IndexWriter 類的 add 方法加入到索引中去。
for(int i=0;i<docs.length;i++) {
indexWriter.addDocument(docs[i]);
}
indexWriter.close();
}

/**
* 搜索
*
* IndexSearcher 是用來在索引庫中進行查詢的
*/
@Test
public void search() throws Exception {

createIndex();

String queryString = "hello"; //搜索關鍵字
//String queryString = "adddocument";

// 1,把要搜索的文本解析爲 Query
//在名爲name和content的字段中搜索queryString
String[] fields = {"name","content" }; //
QueryParser queryParser = new MultiFieldQueryParser(Version.LUCENE_30,fields, analyzer);
Query query = queryParser.parse(queryString);

// 2,進行查詢
IndexSearcher indexSearcher = new IndexSearcher(FSDirectory.open(indexPath));
//Filter暫進不使用
Filter filter = null;
TopDocs topDocs = indexSearcher.search(query, filter, 10000);
System.out.println("總共有【" + topDocs.totalHits + "】條匹配結果");

// 3,打印結果
for (ScoreDoc scoreDoc : topDocs.scoreDocs) {
int docSn = scoreDoc.doc; // 文檔內部編號
Document doc = indexSearcher.doc(docSn); // 根據編號取出相應的文檔
File2DocumentUtils.printDocumentInfo(doc); // 打印出文檔信息
}
}
}

 

File2DocumentUtils.java文件:

 

package com.reiyen.lucene.utils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;

import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.Field.Index;
import org.apache.lucene.document.Field.Store;
import org.apache.lucene.util.NumericUtils;

public class File2DocumentUtils {

// �ļ���name, content, size, path
public static Document[] file2Document(String[] path) {

Document[] docs = new Document[path.length];
for(int i=0;i<path.length;i++) {
File file = new File(path[i]);

Document doc = new Document();
doc.add(new Field("name", file.getName(), Store.YES, Index.ANALYZED));
System.out.println("file.getName(): "+file.getName());
doc.add(new Field("content", readFileContent(file), Store.YES, Index.ANALYZED));
doc.add(new Field("size", NumericUtils.longToPrefixCoded(file.length()), Store.YES, Index.NOT_ANALYZED));
doc.add(new Field("path", file.getAbsolutePath(), Store.YES, Index.NOT_ANALYZED));
docs[i] = doc;
}
return docs;
}

public static String readFileContent(File file) {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
StringBuffer content = new StringBuffer();

for (String line = null; (line = reader.readLine()) != null;) {
content.append(line).append("/n");
}

return content.toString();
} catch (Exception e) {
throw new RuntimeException(e);
}
}

 
public static void printDocumentInfo(Document doc) {
// Field f = doc.getField("name");
// f.stringValue();
System.out.println("------------------------------");
System.out.println("name = " + doc.get("name"));
System.out.println("content = " + doc.get("content"));
System.out.println("size = " + NumericUtils.prefixCodedToLong((doc.get("size"))));
System.out.println("path = " + doc.get("path"));
}

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章