lucene的介紹,這里引用百度百科的介紹Lucene是apache軟件基金會4 jakarta項目組的一個子項目,是一個開放源代碼的全文檢索引擎工具包,即它不是一個完整的全文檢索引擎,而是一個全文檢索引擎的架構,提供了完整的查詢引擎和索引引擎,部分文本分析引擎(英文與德文兩種西方語言)。Lucene的目的是為軟件開發人員提供一個簡單易用的工具包,以方便的在目標系統中實現全文檢索的功能,或者是以此為基礎建立起完整的全文檢索引擎。Lucene是一套用于全文檢索和搜尋的開源程式庫,由Apache軟件基金會支持和提供。Lucene提供了一個簡單卻強大的應用程式接口,能夠做全文索引和搜尋。在java開發環境里Lucene是一個成熟的免費開源工具。就其本身而言,Lucene是當前以及最近幾年最受歡迎的免費Java信息檢索程序庫。人們經常提到信息檢索程序庫,雖然與搜索引擎有關,但不應該將信息檢索程序庫與搜索引擎相混淆。
了解lucene的相關知識直接進入lucene官網 http://lucene.apache.org/
在lucene的官網我們會發現還會有一個solr的開源的軟件,它是基于的一個上層寫的應用,lucene給我提供的是類似sdk的功能,開發人員需要更多的自己寫代碼,而solr相對少些代碼。可想而知,如果使用lucene的話,我們可以更多的自定義自己的搜索
進入上面的lucene的官方網站,找到下載后解壓就行
根據lucene的版本的不同,需要的jdk的版本也會有差異,這個需要在官方網站上看看說明文檔,本次測試使用的lucene4.9,編譯的jdk為1.7
Unsupported major.minor version 51.0 xxx
如果出現類似的異常,就是下載的lucene和編譯的jdk的版本不對,更新個jdk1.7 就可以
下面是在lucene的官方文檔里的一段入門代碼
public class LuceneDemo
{
PRivate static final Version version = Version.LUCENE_4_9;
public static void main(String[] args) throws Exception
{
Analyzer analyzer = new StandardAnalyzer(version);
// Store the index in memory:
Directory directory = new RAMDirectory();
// To store an index on disk, use this instead:
//Directory directory = FSDirectory.open("/tmp/testindex");
IndexWriterConfig config = new IndexWriterConfig(version, analyzer);
IndexWriter iwriter = new IndexWriter(directory, config);
Document doc = new Document();
Document doc2 = new Document();
String text = "This is the text to be indexed.";
String text2 = "This is the text to be indexed22222.";
doc.add(new Field("fieldname", text, TextField.TYPE_STORED));
doc2.add(new Field("fieldname", text2, TextField.TYPE_STORED));
iwriter.addDocument(doc); iwriter.addDocument(doc2); iwriter.close();
// Now search the index:
DirectoryReader ireader = DirectoryReader.open(directory);
IndexSearcher isearcher = new IndexSearcher(ireader);
// Parse a simple query that searches for "text":
QueryParser parser = new QueryParser(version, "fieldname", analyzer);
Query query = parser.parse("text");
ScoreDoc[] hits = isearcher.search(query, null, 1000).scoreDocs;
// Iterate through the results:
for (int i = 0; i < hits.length; i++)
{
Document hitDoc = isearcher.doc(hits[i].doc);
System.out.println("This is the text to be indexed="+hitDoc.get("fieldname"));
}
ireader.close();
directory.close();
}
}
從代碼可以看到基本操作步驟:
Lucene中有幾個重要的元素
比如:一篇文章,我們有title,author,createTime,category,content那么這每一個可以看做一個域,整個文章就是一個document,如果搜索內容content包含了lucene的文件,就會更具域content的所有找到有Lucene的文章。
新聞熱點
疑難解答