lucene的普通搜尋(二)

來源:互聯網
上載者:User

標籤:

首先得到索引:

package com.wp.util;import java.io.File;import java.io.FileReader;import java.nio.file.Paths;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.TextField;import org.apache.lucene.index.IndexWriter;import org.apache.lucene.index.IndexWriterConfig;import org.apache.lucene.store.Directory;import org.apache.lucene.store.FSDirectory;public class Indexer {    private IndexWriter writer; // 寫索引執行個體    /**     * 構造方法 執行個體化IndexWriter     *      * @param indexDir     * @throws Exception     */    public Indexer(String indexDir) throws Exception {        Directory dir = FSDirectory.open(Paths.get(indexDir));// 根據路徑擷取儲存索引的目錄        Analyzer analyzer = new StandardAnalyzer(); // 這裡用了多態,StandardAnalyzer是一個標準分詞器,        IndexWriterConfig iwc = new IndexWriterConfig(analyzer);//將分詞器加入到索引中        writer = new IndexWriter(dir, iwc);    }    /**     * 關閉寫索引     *      * @throws Exception     */    public void close() throws Exception {        writer.close();    }    /**     * 索引指定目錄的所有檔案     *      * @param dataDir     * @throws Exception     */    public int index(String dataDir) throws Exception {        File[] files = new File(dataDir).listFiles();//得到目錄下的所有檔案        for (File f : files) {            indexFile(f);        }        return writer.numDocs();    }    /**     * 索引指定檔案     *      * @param f     */    private void indexFile(File f) throws Exception {        // 關於f.getCanonicalPath()查看http://www.blogjava.net/dreamstone/archive/2007/08/08/134968.html        System.out.println("索引檔案:" + f.getCanonicalPath());//得到絕對路徑        Document doc = getDocument(f);        writer.addDocument(doc);    }    /**     * 擷取文檔,文檔裡再設定每個欄位     *      * @param f     */    private Document getDocument(File f) throws Exception {        Document doc = new Document();//建立文檔        doc.add(new TextField("contents", new FileReader(f)));//以檔案流的形式讀取檔案內容        doc.add(new TextField("fileName", f.getName(), Field.Store.YES));//Field.Store.YES表示將屬性存入記憶體中        doc.add(new TextField("fullPath", f.getCanonicalPath(),Field.Store.YES));//存入記憶體中        return doc;    }    public static void main(String[] args) {        String indexDir = "D:\\lucene\\luceneIndex";        String dataDir = "D:\\lucene\\data";        Indexer indexer = null;        int numIndexed = 0;        long start = System.currentTimeMillis();        try {            indexer = new Indexer(indexDir);//建立索引            numIndexed = indexer.index(dataDir);//索引指定目錄的所有檔案        } catch (Exception e) {            e.printStackTrace();        } finally {            try {                indexer.close();            } catch (Exception e) {                e.printStackTrace();            }        }        long end = System.currentTimeMillis();        System.out.println("索引:" + numIndexed + " 個檔案 花費了" + (end - start)                + " 毫秒");    }}

 增加的知識:

getPath():

返回的是定義時的路徑,可能是相對路徑,也可能是絕對路徑,這個取決於定義時用的是相對路徑還是絕對路徑。如果定義時用的是絕對路徑,那麼使用getPath()返回的結果跟用getAbsolutePath()返回的結果一樣

getAbsolutePath():

返回的是定義時的路徑對應的相對路徑,但不會處理“.”和“..”的情況

getCanonicalPath():

返回的是正常化的絕對路徑,相當於將getAbsolutePath()中的“.”和“..”解析成對應的正確的路徑

搜尋:

package com.wp.util;import java.nio.file.Paths;import org.apache.lucene.analysis.Analyzer;import org.apache.lucene.analysis.standard.StandardAnalyzer;import org.apache.lucene.document.Document;import org.apache.lucene.index.DirectoryReader;import org.apache.lucene.index.IndexReader;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.junit.After;import org.junit.Before;import org.junit.Test;public class SearchTest {    private Directory dir;    private IndexReader reader;    private IndexSearcher is;    @Before    public void setUp() throws Exception {        dir = FSDirectory.open(Paths.get("D:\\lucene\\luceneIndex"));// 得到儲存索引的目錄        reader = DirectoryReader.open(dir);// 讀取索引        is = new IndexSearcher(reader);// //建立索引搜尋    }    @After    public void tearDown() throws Exception {        reader.close();    }    /**     * 對特定項搜尋(只能是指定的字串,而不是其中的字母)     *      * @throws Exception     */    @Test    public void testTermQuery() throws Exception {        String searchField = "contents";        String q = "particular";        Term t = new Term(searchField, q);// 查詢contents中的particular字元        Query query = new TermQuery(t);// 對特定字元查詢        TopDocs hits = is.search(query, 10);// 得到查詢的最前面10條資料        System.out.println("匹配 ‘" + q + "‘,總共查詢到" + hits.totalHits + "個文檔");        for (ScoreDoc scoreDoc : hits.scoreDocs) {            Document doc = is.doc(scoreDoc.doc);// 得到查詢到的得分文檔個數            System.out.println(doc.get("fullPath"));        }    }    /**     * 解析查詢運算式     *      * @throws Exception     */    @Test    public void testQueryParser() throws Exception {        Analyzer analyzer = new StandardAnalyzer(); // 標準分詞器        String searchField = "contents";        // String q = "particular AND SA";//表示查詢都: 注意AND要大寫        // String q = "particular or a";// 表示查詢或者        String q = "particular~";// ~符號表示查詢相近的        QueryParser parser = new QueryParser(searchField, analyzer);        Query query = parser.parse(q);// 進行解析        TopDocs hits = is.search(query, 100);        System.out.println("匹配 " + q + "查詢到" + hits.totalHits + "個記錄");        for (ScoreDoc scoreDoc : hits.scoreDocs) {            Document doc = is.doc(scoreDoc.doc);            System.out.println(doc.get("fullPath"));        }    }}

 

lucene的普通搜尋(二)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.