lucene學習 - 2 - 一個樣本

來源:互聯網
上載者:User

標籤:

接下來我會寫一個lucene的執行個體。實際上在搜尋引擎上隨便搜尋下都能找到這樣的東西。不過還是寫一下吧,這也是我學習的經曆。

package com.zhyea.doggie;import java.io.BufferedReader;import java.io.File;import java.io.FileReader;import java.io.IOException;import org.apache.lucene.analysis.Analyzer;import org.apache.lucene.analysis.standard.StandardAnalyzer;import org.apache.lucene.document.Document;import org.apache.lucene.document.Field;import org.apache.lucene.document.StringField;import org.apache.lucene.document.TextField;import org.apache.lucene.index.DirectoryReader;import org.apache.lucene.index.IndexReader;import org.apache.lucene.index.IndexWriter;import org.apache.lucene.index.IndexWriterConfig;import org.apache.lucene.index.Term;import org.apache.lucene.queryparser.classic.QueryParser;import org.apache.lucene.search.IndexSearcher;import org.apache.lucene.search.Query;import org.apache.lucene.search.ScoreDoc;import org.apache.lucene.search.TermQuery;import org.apache.lucene.search.TopDocs;import org.apache.lucene.store.Directory;import org.apache.lucene.store.FSDirectory;import org.apache.lucene.util.Version;public class LuceneTest {    public static void main(String[] args) {        // 要用來檢索的樣本檔案儲存體路徑        String docPath = "D:\\aqsiqDevelop\\workspace3\\doggie\\WebContent\\docs";        // 索引檔案儲存體路徑        String indexPath = "D:\\aqsiqDevelop\\workspace3\\doggie\\WebContent\\index";        try {            // 分析器,這裡使用了標準分析器            Analyzer analyzer = new StandardAnalyzer();            // 準備好索引儲存目錄            Directory dir = FSDirectory.open(new File(indexPath));            // 建立IndexWriter(索引寫入器)配置,            // 在配置中指明建立IndexWriter使用的lucene的版本及使用的分析器            IndexWriterConfig config = new IndexWriterConfig(Version.LATEST,                    analyzer);            // 建立IndexWriter(索引寫入器),並指明索引儲存路徑和設定檔            IndexWriter writer = new IndexWriter(dir, config);            // 使用IndexWriter(索引寫入器)建立索引,這裡另外建立一個方法            addDocuments(docPath, writer);                        /* -------------建立索引結束,以下是進行搜尋------------ */            // 建立索引讀出器            IndexReader reader = DirectoryReader.open(dir);            // 建立搜尋器            IndexSearcher seacher = new IndexSearcher(reader);            // 建立搜尋對象            Query query = new TermQuery(new Term("content", "楊過"));            // 執行搜尋,並返回結果            TopDocs topDocs = seacher.search(query, 10000);            // 展示搜尋結果            Document doc;            for(ScoreDoc tmp : topDocs.scoreDocs){                doc = reader.document(tmp.doc);                System.out.println("書名:" + doc.get("name")                                  + "---------------------"                                 + "路徑:" + doc.get("path"));            }        } catch (Exception e) {            e.printStackTrace();        }    }    /**     * 遍曆樣本文本所在的目錄,進行分析。      * 這裡採用的樣本文本是金庸的三部小說:神鵰、射鵰和笑傲江湖。     * @param docPath     *            樣本文本儲存路徑     * @param writer     *            索引寫入器     * @throws IOException     */    private static void addDocuments(String docPath, IndexWriter writer)            throws IOException {        File dir = new File(docPath);        for (File tmp : dir.listFiles()) {            //建立Document對象,代表一個被索引的基本單元            Document doc = new Document();            String fileName = tmp.getName();            String filePath = tmp.getCanonicalPath();                    String fileContent = readTxt(tmp);            //建立Field,並加入Document            doc.add(new StringField("name", fileName,   Field.Store.YES));            doc.add(new StringField("path", filePath,   Field.Store.YES));            doc.add(new TextField("content",fileContent,Field.Store.YES));            //將Document從記憶體寫入真實目錄            writer.addDocument(doc);            //提交索引,將索引寫入索引檔案,這個別忘了            writer.commit();        }    }    /**     * 換行標誌符     */    static final String NEWLINE = System.getProperty("line.separator");    /**     * 讀取txt檔案     *      * @param file     *            txt檔案對象     * @return     * @throws IOException     */    private static String readTxt(File file) throws IOException {        BufferedReader br = null;        try {            br = new BufferedReader(new FileReader(file));            StringBuilder builder = new StringBuilder();            String line;            while (null != (line = br.readLine())) {                builder.append(line).append(NEWLINE);            }            return builder.toString();        } finally {            if (null != br) br.close();        }    }}

執行代碼,發現沒有任何輸出。用luke進行查看索引目錄,發現content對應的是亂碼:

在讀取txt檔案時,需要調整編碼格式,或者直接調整txt的編碼格式與工作空間預設編碼相同即可。

這裡就不寫出了。

調整亂碼後,再次執行程式,發現還是不能檢索出什麼東西。再次查看索引目錄:

所有的中文字元都被分開成為單獨的Term。這次需要調整分析器,將分析器調整為CJKAnalyzer。這次能夠檢索出結果了:

實際上,影響查詢結果的不只是分析器,還有這一句:

new TermQuery(new Term("content", "楊過"));

好了,這些可以留到以後再說。

all。

lucene學習 - 2 - 一個樣本

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.