Lucene全文檢索索引初識

來源:互聯網
上載者:User

標籤:

Lucene 簡述
Lucene是一個開放原始碼的全文檢索索引引擎工具包,但它不是一個完整的全文檢索索引引擎,而是一個全文檢索索引引擎的架構,提供了完整的查詢引擎和索引引擎,部分文本分析引擎。

資料可以三種:

  • 結構化資料(具有固定格式或有限長度的資料)
  • 非結構化資料
  • 半結構化資料

對於結構化資料一般使用SQL語句查詢,而非結構化資料有順序掃描和全文檢索索引。

Lucene 檔案結構
階層:索引 -> 段 -> 文檔 -> 域 -> 詞
文檔是Lucene索引和搜尋的原子單位,文檔為包括一個或多個域的容器,域則真正包括被搜尋的內容,域值通過分詞技術處理,得到多個詞元。

Lucene 索引建立
建立索引的三步:需要檢索的資料(Document)、分詞技術(Analyzer)、索引建立(indexer)

//建立索引關鍵類//IndexWriteIndexWrite indexWrite=new IndexWrite(directory,indexWriteConfig);//DirectoryDirectory directory=FSDirectory.open(new File("C://index));//Analyzer  建立標準分詞器Analyzer analyzer=new StandardAnalyzer(Version.LUCENE_43);//DocumentDocument doc=new Document();//Fileddoc.add(new TextField("filedname","測試",Store.YES));

Java實現索引建立

package com.lucene;import org.apache.lucene.analysis.Analyzer;import org.apache.lucene.analysis.standard.StandardAnalyzer;import org.apache.lucene.document.*;import org.apache.lucene.index.IndexWriter;import org.apache.lucene.index.IndexWriterConfig;import org.apache.lucene.store.Directory;import org.apache.lucene.store.FSDirectory;import org.apache.lucene.util.Version;import java.io.File;import java.io.IOException;/** * Created with IntelliJ IDEA. * User: YEN * Date: 2016/8/17 * Time: 08:26 *//** * 索引建立 */public class IndexCreate {    public static void main(String[] args) throws IOException {        //指定分詞技術,這裡使用的是標準分詞        Analyzer analyzer=new StandardAnalyzer(Version.LUCENE_43);        //indexWriter的配置資訊        IndexWriterConfig indexWriterConfig=new IndexWriterConfig(Version.LUCENE_43,analyzer);        //索引的開啟檔案:沒有就建立,有就開啟        indexWriterConfig.setOpenMode(IndexWriterConfig.OpenMode.CREATE_OR_APPEND);        Directory directory=null;        IndexWriter indexWriter=null;        try{            //確定索引檔案的位置 這裡是本地檔案儲存體            directory= FSDirectory.open(new File("C://index"));            //如果索引處於鎖定狀態就解鎖            if(indexWriter.isLocked(directory)){                indexWriter.unlock(directory);            }            //指定索引的操作對象為indexWrite            indexWriter = new IndexWriter(directory, indexWriterConfig);        }catch ( Exception e ){            e.printStackTrace();        }finally {            indexWriter.close();            directory.close();        }        Document doc1=new Document();        //StringField域        doc1.add(new StringField("id","abc", Field.Store.YES));        //TextField域,採用指定的分詞技術        doc1.add(new TextField("content","Lucene測試", Field.Store.YES));        //IntField域        doc1.add(new IntField("num",1, Field.Store.YES));        //將文檔寫入到索引中        indexWriter.addDocument(doc1);        indexWriter.commit();    }}

Lucene 索引檢索
索引檢索的四步:搜尋索引鍵(Keywords)、分詞技術(Analyzer)、檢索索引(Search)、返回結果。

java實現索引檢索

package com.lucene;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.queryparser.classic.ParseException;import org.apache.lucene.queryparser.classic.QueryParser;import org.apache.lucene.search.IndexSearcher;import org.apache.lucene.search.Query;import org.apache.lucene.search.TopDocs;import org.apache.lucene.store.Directory;import org.apache.lucene.store.FSDirectory;import org.apache.lucene.util.Version;import java.io.File;import java.io.IOException;/** * Created with IntelliJ IDEA. * User: YEN * Date: 2016/8/17 * Time: 08:42 */public class IndexSearch {    public static void main(String[] args) {        Directory directory=null;        try {            //索引硬碟儲存路徑            directory= FSDirectory.open(new File("C://index"));            //讀取索引            DirectoryReader directoryReader=DirectoryReader.open(directory);            //建立索引檢索對象            IndexSearcher search=new IndexSearcher(directoryReader);            //分詞技術            Analyzer analyzer=new StandardAnalyzer(Version.LUCENE_43);            //建立Query            QueryParser parser=new QueryParser(Version.LUCENE_43,"content",analyzer);            Query query=parser.parse("Lucene案例");            //檢索索引,擷取合格前10條記錄            TopDocs topDocs=search.search(query,10);            if(null!=topDocs){                System.out.println(topDocs.totalHits);                for ( int i = 0; i < topDocs.scoreDocs.length; i++ ) {                    Document doc=search.doc(topDocs.scoreDocs[i].doc);                    System.out.println("id="+doc.get("id"));                    System.out.println("content="+doc.get("content"));                }            }            directory.close();            directoryReader.close();        } catch ( IOException e ) {            e.printStackTrace();        } catch ( ParseException e ) {            e.printStackTrace();        }    }}

Lucene 分詞器

常用分詞器:

  • StandardAnalyzer 標準分詞器
  • IKAnalyzer 基於Lucene的第三方中文分詞技術
  • WritespaceAnalyzer 空格分詞器
  • SimpleAnalyzer 簡單分詞器
  • CJKAnalyzer 二分法分詞器
  • KeywordAnalyzer 關鍵詞分詞器
  • StopAnalyzer 被忽略詞分詞器
package com.lucene;import org.apache.lucene.analysis.Analyzer;import org.apache.lucene.analysis.TokenStream;import org.apache.lucene.analysis.cjk.CJKAnalyzer;import org.apache.lucene.analysis.core.KeywordAnalyzer;import org.apache.lucene.analysis.core.SimpleAnalyzer;import org.apache.lucene.analysis.core.StopAnalyzer;import org.apache.lucene.analysis.core.WhitespaceAnalyzer;import org.apache.lucene.analysis.standard.StandardAnalyzer;import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;import org.apache.lucene.util.Version;import org.wltea.analyzer.lucene.IKAnalyzer;import java.io.IOException;import java.io.StringReader;/** * Created with IntelliJ IDEA. * User: YEN * Date: 2016/8/17 * Time: 08:57 */public class AnalyzerDemo {    private static String str="Lucene案例開發";    public static void main(String[] args) {        //定義分詞器對象        Analyzer analyzer=null;        analyzer=new StandardAnalyzer(Version.LUCENE_43);        AnalyzerDemo.Show(analyzer);        System.out.println("\n....................................");        AnalyzerDemo.Show(new IKAnalyzer());        System.out.println("\n....................................");        AnalyzerDemo.Show(new WhitespaceAnalyzer(Version.LUCENE_43));        System.out.println("\n....................................");        AnalyzerDemo.Show(new SimpleAnalyzer(Version.LUCENE_43));        System.out.println("\n....................................");        AnalyzerDemo.Show(new CJKAnalyzer(Version.LUCENE_43));        System.out.println("\n....................................");        AnalyzerDemo.Show(new KeywordAnalyzer());        System.out.println("\n....................................");        AnalyzerDemo.Show(new StopAnalyzer(Version.LUCENE_43));    }    //輸出分詞結果    public static void Show(Analyzer analyzer){        StringReader stringReader=new StringReader(str);        try {            TokenStream tokenStream=analyzer.tokenStream("",stringReader);            tokenStream.reset();            CharTermAttribute termAttribute=tokenStream.getAttribute(CharTermAttribute.class);            System.out.println("分詞技術:"+analyzer.getClass());            while ( tokenStream.incrementToken() ){                System.out.print(termAttribute.toString()+"|");            }        } catch ( IOException e ) {            e.printStackTrace();        }    }}

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.