lucene 5.2.0學習筆記

來源:互聯網
上載者:User

標籤:用法   autowire   set   comm   cto   mod   order   useful   factor   


package com.bc.cas.manager;
import com.bc.cas.dao.BookDao;import com.bc.cas.model.entity.Book;import com.google.common.base.Objects;import com.google.common.collect.Lists;import org.apache.log4j.helpers.LogLog;import org.apache.lucene.analysis.Analyzer;import org.apache.lucene.analysis.cn.smart.SmartChineseAnalyzer;import org.apache.lucene.analysis.util.CharArraySet;import org.apache.lucene.document.*;import org.apache.lucene.index.*;import org.apache.lucene.queryparser.classic.ParseException;import org.apache.lucene.queryparser.classic.QueryParser;import org.apache.lucene.search.*;import org.apache.lucene.store.FSDirectory;import org.junit.Test;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Repository;import org.springframework.util.CollectionUtils;
import java.io.IOException;import java.nio.file.Paths;import java.util.Arrays;import java.util.Iterator;import java.util.List;

/** * @Copyright 2012-2016 duenboa 著作權 * @Author Created by Administrator on 2016/11/29. * @Version V 1.0.0 * @Desc 索引管理器 */
@Repositorypublic class IndexManager {
    @Autowired    private BookDao bookDao;
    static FSDirectory dir;
    static {        try {            dir = FSDirectory.open(Paths.get("d:/lucene/lucene052_index05"));        } catch (IOException e) {            e.printStackTrace();        }    }

    /**     * 建立索引 -common     */    @Test    public void createIndex(List<Document> docs) throws IOException {
        if (docs == null) {            return;        }
        // 自訂停用詞        List<String> strings = Arrays.asList("的", "在", "了", "呢", ",", "0", ":", ",", "是", "這", "那", "麼");        CharArraySet unUsefulWorlds = new CharArraySet(strings, true);
        // 加入系統預設停用詞        Iterator<Object> itor = SmartChineseAnalyzer.getDefaultStopSet().iterator();        while (itor.hasNext()) unUsefulWorlds.add(itor.next());        //指定了停用詞的分詞器        Analyzer analyzer = new SmartChineseAnalyzer(unUsefulWorlds);
        IndexWriterConfig config = new IndexWriterConfig(analyzer);        IndexWriter writer = new IndexWriter(dir, config);
        writer.addDocuments(docs);        writer.commit();        writer.close();    }

    /**     * 執行查詢 -common     *     * @param query     * @throws IOException     * @throws ParseException     */    private static void doQuery(Query query) throws IOException, ParseException {        IndexReader reader = DirectoryReader.open(dir);        IndexSearcher searcher = new IndexSearcher(reader);
        //執行query,擷取指定條數的頂行記錄        TopDocs topDocs = searcher.search(query, 10);        System.out.println("搜尋出的總記錄數為: " + topDocs.totalHits);
        //評分文檔集合        ScoreDoc[] docs = topDocs.scoreDocs;        for (ScoreDoc doc : docs) {            //擷取文檔id            int id = doc.doc;            //根據文檔id查詢文檔對象            Document document = searcher.doc(id);
            //列印資訊            System.out.println(                    Objects.toStringHelper("docuemnt")                            .add("文檔id", document.get("id"))                            .add("文檔名稱", document.get("name"))                            .add("文檔圖片", document.get("pic"))                            .add("文檔描述", document.get("description"))                            .toString());        }        reader.close();    }

    /**     * 測試建立索引     */    public void testCreateIndex() {        List<Book> bookList = bookDao.findAll();        if (CollectionUtils.isEmpty(bookList)) return;
        List<Document> docList = Lists.newArrayList();        Document doc;        for (Book book : bookList) {            doc = new Document();            doc.add(new StoredField("id", book.getId()));            doc.add(new StringField("name", book.getName(), Field.Store.YES));            doc.add(new TextField("pic", book.getPic(), Field.Store.YES));            doc.add(new TextField("description", book.getDescription(), Field.Store.YES));            docList.add(doc);        }
        try {            createIndex(docList);        } catch (IOException e) {            LogLog.error(e.getMessage(), e);        }    }
    /**     *     * 查詢     *     * @throws IOException     */    @Test    public static void testQuery() throws IOException, ParseException {        QueryParser parser = new QueryParser("description", new SmartChineseAnalyzer());        Query query = parser.parse("description:java AND lucene");        doQuery(query);    }

}



Field類的子類和說明, 以及用法:
StoredField(FieldName, FieldValue) 

重載,支援多種類型
 不分詞
不索引 
樣本:
StringField(FieldName,  String FieldValue, Store.YES)

 字串類型資料 
不分詞    
索引 
樣本: 訂單號, id, 手機號等
LongField(FieldName, Long FieldValue,   Store.YES) 

Long型資料    
 分詞
索引 
 樣本: 價格
TextField(FieldName, FieldValue, Store.YES)    或 TextField(FieldName, Reader)

字串或者流 
 分詞
索引 
















來自為知筆記(Wiz)

lucene 5.2.0學習筆記

聯繫我們

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