日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Lucene第一讲——概述与入门

發(fā)布時(shí)間:2025/3/15 编程问答 18 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Lucene第一讲——概述与入门 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

一、概述

  1.什么是Lucene?

    Lucene是apache下的一個(gè)開源的全文檢索引擎工具包

    它為軟件開發(fā)人員提供一個(gè)簡單易用的工具包(類庫),以方便的在目標(biāo)系統(tǒng)中實(shí)現(xiàn)全文檢索的功能。

  2.能干什么?

    主要運(yùn)用:全文檢索

  3.全文檢索定義   

    全文檢索首先將要查詢的目標(biāo)文檔中的詞提取出來,組成索引,通過查詢索引達(dá)到搜索目標(biāo)文檔的目的。這種先建立索引,再對索引進(jìn)行搜索的過程就叫全文檢索(Full-text Search

?二、實(shí)現(xiàn)流程

  

?

  流程主要分為:索引流程  搜索流程

三、入門程序  

  1.準(zhǔn)備數(shù)據(jù)(數(shù)據(jù)庫)

  

  2.引入依賴(使用maven)

<!--版本管理--><properties><lucene.version>5.3.1</lucene.version><junit.version>4.12</junit.version></properties><dependencies><!-- lucene-core --><dependency><groupId>org.apache.lucene</groupId><artifactId>lucene-core</artifactId><version>${lucene.version}</version></dependency><!-- lucene-query-parser --><dependency><groupId>org.apache.lucene</groupId><artifactId>lucene-queryparser</artifactId><version>${lucene.version}</version></dependency><!-- lucene-analyzers-common --><dependency><groupId>org.apache.lucene</groupId><artifactId>lucene-analyzers-common</artifactId><version>${lucene.version}</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>${junit.version}</version><scope>test</scope></dependency></dependencies> View Code

  //使用數(shù)據(jù)庫作為數(shù)據(jù)源請?zhí)砑訑?shù)據(jù)庫依賴

  3.其它:如JDK(7及以上),mysql等不再贅述

  4.索引流程

    1.為什么采集數(shù)據(jù)

  全文檢索搜索的內(nèi)容的格式是多種多樣的,比如:視頻、mp3、圖片文檔等等。對于這種格式不同的數(shù)據(jù),需要先將他們采集到本地,然后統(tǒng)一封裝到lucene的文檔對象中,也就是說需要將存儲(chǔ)的內(nèi)容進(jìn)行統(tǒng)一才能對它進(jìn)行查詢。

    2.采集數(shù)據(jù)的方式

  l?對于互聯(lián)網(wǎng)中的數(shù)據(jù),使用爬蟲工具(http工具)將網(wǎng)頁爬取到本地

  l?對于數(shù)據(jù)庫中的數(shù)據(jù)使用jdbc程序進(jìn)行數(shù)據(jù)采集

  l?對于文件系統(tǒng)的數(shù)據(jù),使用io流采集

    常用數(shù)據(jù)采集爬蟲工具(了解):

Solr(http://lucene.apache.org/solr) ,solr是apache的一個(gè)子項(xiàng)目,支持從關(guān)系數(shù)據(jù)庫、xml文檔中提取原始數(shù)據(jù)。

Nutch(http://lucene.apache.org/nutch), Nutch是apache的一個(gè)子項(xiàng)目,包括大規(guī)模爬蟲工具,能夠抓取和分辨web網(wǎng)站數(shù)據(jù)。

jsoup(http://jsoup.org/?),jsoup 是一款Java 的HTML解析器,可直接解析某個(gè)URL地址、HTML文本內(nèi)容。它提供了一套非常省力的API,可通過DOM,CSS以及類似于jQuery的操作方法來取出和操作數(shù)據(jù)。

heritrix(http://sourceforge.net/projects/archive-crawler/files/),Heritrix 是一個(gè)由 java 開發(fā)的、開源的網(wǎng)絡(luò)爬蟲,用戶可以使用它來從網(wǎng)上抓取想要的資源。其最出色之處在于它良好的可擴(kuò)展性,方便用戶實(shí)現(xiàn)自己的抓取邏輯。

    3.索引文件邏輯結(jié)構(gòu)

    

?

?  與字典的 結(jié)構(gòu)類似,一邊目錄一邊文檔,目錄是索引域,文檔是lucene封裝的統(tǒng)一文檔格式 

    文檔域

      文檔域存儲(chǔ)的信息就是采集到的信息通過Document對象來存儲(chǔ)具體說是通過Document對象中field域來存儲(chǔ)數(shù)據(jù)

      比如數(shù)據(jù)庫中一條記錄會(huì)存儲(chǔ)一個(gè)一個(gè)Document對象數(shù)據(jù)庫中一列會(huì)存儲(chǔ)成Document中一個(gè)field

      文檔域中,Document對象之間是沒有關(guān)系的而且每個(gè)Document中的field域也不一定一樣 

    ?索引域

      索引域主要是為了搜索使用的索引域內(nèi)容是經(jīng)過lucene分詞之后存儲(chǔ)的

    倒排索引表

      傳統(tǒng)方法是先找到文件,如何在文件中找內(nèi)容,在文件內(nèi)容中匹配搜索關(guān)鍵字,這種方法是順序掃描方法,數(shù)據(jù)量大就搜索慢。

      倒排索引結(jié)構(gòu)是根據(jù)內(nèi)容(詞語)找文檔,倒排索引結(jié)構(gòu)也叫反向索引結(jié)構(gòu),包括索引和文檔兩部分,索引即詞匯表,它是在索引中匹配搜索關(guān)鍵字,由于索引內(nèi)容量有限并且采用固定優(yōu)化算法搜索速度很快,找到了索引中的詞匯,詞匯與文檔關(guān)聯(lián),從而最終找到了文檔。

    

  5.索引

?    1.采集數(shù)據(jù)

    對應(yīng)上文數(shù)據(jù)庫的PO類:

package com.itheima.lucene.po;/*** ?* <p>* Title:?Book* </p>* ?* <p>* Description:?TODO(這里用一句話描述這個(gè)類的作用)?* <p>* <p>* Company: www.itcast.com* </p>* ?@author?傳智.關(guān)云長? ?@date?2015-12-27?上午10:03:11?? ?@version 1.0*/ public class Book {// 圖書IDprivate Integer id;// 圖書名稱private String name;// 圖書價(jià)格private Float price;// 圖書圖片private String pic;// 圖書描述private String description;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Float getPrice() {return price;}public void setPrice(Float price) {this.price = price;}public String getPic() {return pic;}public void setPic(String pic) {this.pic = pic;}public String getDescription() {return description;}public void setDescription(String description) {this.description = description;}} View Code

    使用傳統(tǒng)JDBC從數(shù)據(jù)庫采集數(shù)據(jù)進(jìn)行封裝:

package com.itheima.lucene.dao;import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List;import com.itheima.lucene.po.Book;/*** ?* <p>* Title:?BookDaoImpl* </p>* ?* <p>* Description:?TODO(這里用一句話描述這個(gè)類的作用)?* <p>* <p>* Company: www.itcast.com* </p>* ?@author?傳智.關(guān)云長? ?@date?2015-12-27?上午10:04:30?? ?@version 1.0*/ public class BookDaoImpl implements BookDao {@Overridepublic List<Book> queryBooks() {// 數(shù)據(jù)庫鏈接Connection connection = null;// 預(yù)編譯statementPreparedStatement preparedStatement = null;// 結(jié)果集ResultSet resultSet = null;// 圖書列表List<Book> list = new ArrayList<Book>();try {// 加載數(shù)據(jù)庫驅(qū)動(dòng)Class.forName("com.mysql.jdbc.Driver");// 連接數(shù)據(jù)庫connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/solr", "root", "root");// SQL語句String sql = "SELECT * FROM book";// 創(chuàng)建preparedStatementpreparedStatement = connection.prepareStatement(sql);// 獲取結(jié)果集resultSet = preparedStatement.executeQuery();// 結(jié)果集解析while (resultSet.next()) {Book book = new Book();book.setId(resultSet.getInt("id"));book.setName(resultSet.getString("name"));book.setPrice(resultSet.getFloat("price"));book.setPic(resultSet.getString("pic"));book.setDescription(resultSet.getString("description"));list.add(book);}} catch (Exception e) {e.printStackTrace();}return list;}} View Code

    2.創(chuàng)建索引

    

    Document就是封裝數(shù)據(jù)的文檔對象

    IndexWriter是索引過程的核心組件,通過IndexWriter可以創(chuàng)建新索引、更新索引、刪除索引操作。IndexWriter需要通過Directory對索引進(jìn)行存儲(chǔ)操作。

    Directory描述了索引的存儲(chǔ)位置,底層封裝了I/O操作,負(fù)責(zé)對索引進(jìn)行存儲(chǔ)。它是一個(gè)抽象類,它的子類常用的包括FSDirectory(在文件系統(tǒng)存儲(chǔ)索引)、RAMDirectory(在內(nèi)存存儲(chǔ)索引)。

?    創(chuàng)建索引過程:

  ?// 采集數(shù)據(jù)  // 將采集到的數(shù)據(jù)封裝到Document對象中  // 創(chuàng)建分詞器,標(biāo)準(zhǔn)分詞器  // 創(chuàng)建IndexWriter

  // 指定索引庫的地址  // 通過IndexWriter對象將Document寫入到索引庫中  // 關(guān)閉writer

package com.itheima.lucene.first;import java.io.File; import java.util.ArrayList; import java.util.List;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.Field.Store; import org.apache.lucene.document.FloatField; import org.apache.lucene.document.StoredField; import org.apache.lucene.document.StringField; import org.apache.lucene.document.TextField; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriterConfig; import org.apache.lucene.index.Term; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; import org.apache.lucene.util.Version; import org.junit.Test; import org.wltea.analyzer.lucene.IKAnalyzer;import com.itheima.lucene.dao.BookDao; import com.itheima.lucene.dao.BookDaoImpl; import com.itheima.lucene.po.Book;/*** ?* <p>* Title:?IndexManager* </p>* ?* <p>* Description:?TODO(這里用一句話描述這個(gè)類的作用)?* <p>* <p>* Company: www.itcast.com* </p>* ?@author?傳智.關(guān)云長? ?@date?2015-12-27?上午10:08:12?? ?@version 1.0*/ public class IndexManager {@Testpublic void createIndex() throws Exception {// 采集數(shù)據(jù)BookDao dao = new BookDaoImpl();List<Book> list = dao.queryBooks();// 將采集到的數(shù)據(jù)封裝到Document對象中List<Document> docList = new ArrayList<>();Document document;for (Book book : list) {document = new Document();// store:如果是yes,則說明存儲(chǔ)到文檔域中// 圖書ID// 不分詞、索引、存儲(chǔ) StringFieldField id = new StringField("id", book.getId().toString(), Store.YES);// 圖書名稱// 分詞、索引、存儲(chǔ) TextFieldField name = new TextField("name", book.getName(), Store.YES);// 圖書價(jià)格// 分詞、索引、存儲(chǔ) 但是是數(shù)字類型,所以使用FloatFieldField price = new FloatField("price", book.getPrice(), Store.YES);// 圖書圖片地址// 不分詞、不索引、存儲(chǔ) StoredFieldField pic = new StoredField("pic", book.getPic());// 圖書描述// 分詞、索引、不存儲(chǔ) TextFieldField description = new TextField("description",book.getDescription(), Store.NO);// 設(shè)置boost值if (book.getId() == 4)description.setBoost(100f);// 將field域設(shè)置到Document對象中 document.add(id);document.add(name);document.add(price);document.add(pic);document.add(description);docList.add(document);}// 創(chuàng)建分詞器,標(biāo)準(zhǔn)分詞器// Analyzer analyzer = new StandardAnalyzer();// 使用ikanalyzerAnalyzer analyzer = new IKAnalyzer();// 創(chuàng)建IndexWriterIndexWriterConfig cfg = new IndexWriterConfig(Version.LUCENE_4_10_3,analyzer);// 指定索引庫的地址File indexFile = new File("E:\\11-index\\hm19\\");Directory directory = FSDirectory.open(indexFile);IndexWriter writer = new IndexWriter(directory, cfg);// 通過IndexWriter對象將Document寫入到索引庫中for (Document doc : docList) {writer.addDocument(doc);}// 關(guān)閉writer writer.close();}@Testpublic void deleteIndex() throws Exception {// 創(chuàng)建分詞器,標(biāo)準(zhǔn)分詞器Analyzer analyzer = new StandardAnalyzer();// 創(chuàng)建IndexWriterIndexWriterConfig cfg = new IndexWriterConfig(Version.LUCENE_4_10_3,analyzer);Directory directory = FSDirectory.open(new File("E:\\11-index\\hm19\\"));// 創(chuàng)建IndexWriterIndexWriter writer = new IndexWriter(directory, cfg);// Terms// writer.deleteDocuments(new Term("id", "1"));// 刪除全部(慎用) writer.deleteAll();writer.close();}@Testpublic void updateIndex() throws Exception {// 創(chuàng)建分詞器,標(biāo)準(zhǔn)分詞器Analyzer analyzer = new StandardAnalyzer();// 創(chuàng)建IndexWriterIndexWriterConfig cfg = new IndexWriterConfig(Version.LUCENE_4_10_3,analyzer);Directory directory = FSDirectory.open(new File("E:\\11-index\\hm19\\"));// 創(chuàng)建IndexWriterIndexWriter writer = new IndexWriter(directory, cfg);// 第一個(gè)參數(shù):指定查詢條件// 第二個(gè)參數(shù):修改之后的對象// 修改時(shí)如果根據(jù)查詢條件,可以查詢出結(jié)果,則將以前的刪掉,然后覆蓋新的Document對象,如果沒有查詢出結(jié)果,則新增一個(gè)Document// 修改流程即:先查詢,再刪除,在添加Document doc = new Document();doc.add(new TextField("name", "lisi", Store.YES));writer.updateDocument(new Term("name", "zhangsan"), doc);writer.close();} } View Code

  模擬:

package com.itheima.lucene;import com.itheima.lucene.PO.Book; 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.index.IndexableField; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory;import java.io.File; import java.io.IOException; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List;/*** Lucene的入門程序* 作者: Administrator* 日期: 2017/9/6**/ public class LuceneFirst {public static void main(String[] args) throws IOException {// 模擬采集數(shù)據(jù)List<Book> bookList = new ArrayList<>();Book book1 = new Book(1, "java", 100f, "pic1", "java入門書籍");Book book2 = new Book(2, "C", 100.6f, "pic2", "C語言入門書籍");Book book3 = new Book(3, "python", 90.7f, "pic3", "python入門書籍");bookList.add(book1);bookList.add(book2);bookList.add(book3);// 封裝數(shù)據(jù)到Document對象中List<Document> docList = new ArrayList<>();Document doc;for (Book book : bookList) {doc = new Document();// 創(chuàng)建文檔中的Field域,Store可以確定是否存儲(chǔ)到文檔域中Field idField = new TextField("id", book.getId().toString(), Field.Store.YES);Field nameField = new TextField("name", book.getName(), Field.Store.YES);Field priceField = new TextField("price", book.getPrice().toString(), Field.Store.YES);Field picField = new TextField("pic", book.getPic(), Field.Store.YES);Field descriptionField = new TextField("description", book.getDescription(), Field.Store.YES);// 將域放入文檔中 doc.add(idField);doc.add(nameField);doc.add(priceField);doc.add(picField);doc.add(descriptionField);// 將文檔放入文檔列表 docList.add(doc);}// 創(chuàng)建分詞器Analyzer analyzer = new StandardAnalyzer();// 創(chuàng)建IndexWriterIndexWriterConfig conf = new IndexWriterConfig(analyzer);String path = "D:\\BdiduYunDownload\\lucene\\index";Directory dir = FSDirectory.open(Paths.get(path));IndexWriter indexWriter = new IndexWriter(dir, conf);// 通過索引寫對象將docList寫入索引庫for (Document document : docList) {indexWriter.addDocument(document);}// 流的關(guān)閉 indexWriter.close();} } View Code

  索引文件:

  

?

?  6.分詞過程

    Lucene中分詞主要分為兩個(gè)步驟分詞過濾   

     分詞field域中的內(nèi)容一個(gè)個(gè)的分詞

    過濾將分好的詞進(jìn)行過濾比如去掉標(biāo)點(diǎn)符號(hào)大寫轉(zhuǎn)小寫詞的型還原(復(fù)數(shù)轉(zhuǎn)單數(shù)、過去式轉(zhuǎn)成現(xiàn)在式)、停用詞過濾(沒有去重過濾)

    停用詞單獨(dú)應(yīng)用沒有特殊意義的詞比如的英文中的this is a the等等

    分詞示例講解:

?要分詞的內(nèi)容 Lucene is a Java full-text search engine. 分詞 Lucene is a Java Full - text search engine .過濾去掉標(biāo)點(diǎn)符號(hào) Lucene is a Java Full text search engine去掉停用詞 Lucene Java Full text search engine大寫轉(zhuǎn)小寫 lucene java full text search engine View Code

    語匯單元生成過程:

  

  同一個(gè)域中相同的語匯單元(Token)對應(yīng)同一個(gè)Term(詞),它記錄了語匯單元的內(nèi)容及所在域的域名等,還包括來該token出現(xiàn)的頻率及位置。

  不同的域中拆分出來的相同的單詞對應(yīng)不同的term。

  ?相同的域中拆分出來的相同的單詞對應(yīng)相同的term。

  例如:圖書信息里面,圖書名稱中的java和圖書描述中的java對應(yīng)不同的term

?  使用luke工具可以查看索引信息

?  7.搜索流程

    1.輸入查詢語句  

    同數(shù)據(jù)庫的sql一樣,lucene全文檢索也有固定的語法:

    最基本的有比如:AND, OR, NOT 等

    舉個(gè)例子,用戶想找一個(gè)description中包括java關(guān)鍵字和lucene關(guān)鍵字的文檔。

    它對應(yīng)的查詢語句:description:java?AND lucene

    2.搜索流程:

    

    3.代碼實(shí)現(xiàn):

package com.itheima.lucene.first;import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Map;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.MultiFieldQueryParser; import org.apache.lucene.queryparser.classic.QueryParser; import org.apache.lucene.search.BooleanClause.Occur; import org.apache.lucene.search.BooleanQuery; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.NumericRangeQuery; 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.Test;/*** ?* <p>* Title:?IndexSearch* </p>* ?* <p>* Description:?TODO(這里用一句話描述這個(gè)類的作用)?* <p>* <p>* Company: www.itcast.com* </p>* ?@author?傳智.關(guān)云長? ?@date?2015-12-27?上午11:05:35?? ?@version 1.0*/ public class IndexSearch {private void doSearch(Query query) {// 創(chuàng)建IndexSearcher// 指定索引庫的地址try {File indexFile = new File("E:\\11-index\\hm19\\");Directory directory = FSDirectory.open(indexFile);IndexReader reader = DirectoryReader.open(directory);IndexSearcher searcher = new IndexSearcher(reader);// 通過searcher來搜索索引庫// 第二個(gè)參數(shù):指定需要顯示的頂部記錄的N條TopDocs topDocs = searcher.search(query, 10);// 根據(jù)查詢條件匹配出的記錄總數(shù)int count = topDocs.totalHits;System.out.println("匹配出的記錄總數(shù):" + count);// 根據(jù)查詢條件匹配出的記錄ScoreDoc[] scoreDocs = topDocs.scoreDocs;for (ScoreDoc scoreDoc : scoreDocs) {// 獲取文檔的IDint docId = scoreDoc.doc;// 通過ID獲取文檔Document doc = searcher.doc(docId);System.out.println("商品ID:" + doc.get("id"));System.out.println("商品名稱:" + doc.get("name"));System.out.println("商品價(jià)格:" + doc.get("price"));System.out.println("商品圖片地址:" + doc.get("pic"));System.out.println("==========================");// System.out.println("商品描述:" + doc.get("description")); }// 關(guān)閉資源 reader.close();} catch (IOException e) {e.printStackTrace();}}@Testpublic void indexSearch() throws Exception {// 創(chuàng)建query對象// 使用QueryParser搜索時(shí),需要指定分詞器,搜索時(shí)的分詞器要和索引時(shí)的分詞器一致// 第一個(gè)參數(shù):默認(rèn)搜索的域的名稱QueryParser parser = new QueryParser("description",new StandardAnalyzer());// 通過queryparser來創(chuàng)建query對象// 參數(shù):輸入的lucene的查詢語句(關(guān)鍵字一定要大寫)Query query = parser.parse("description:java AND lucene");doSearch(query);}@Testpublic void termQuery() {// 創(chuàng)建TermQuery對象Query query = new TermQuery(new Term("description", "java"));doSearch(query);}@Testpublic void numericRangeQuery() {// 創(chuàng)建NumericRangeQuery對象// 參數(shù):域的名稱、最小值、最大值、是否包含最小值、是否包含最大值Query query = NumericRangeQuery.newFloatRange("price", 55f, 60f, true,false);doSearch(query);}@Testpublic void booleanQuery() {// 創(chuàng)建BooleanQueryBooleanQuery query = new BooleanQuery();// 創(chuàng)建TermQuery對象Query q1 = new TermQuery(new Term("description", "lucene"));// 創(chuàng)建NumericRangeQuery對象// 參數(shù):域的名稱、最小值、最大值、是否包含最小值、是否包含最大值Query q2 = NumericRangeQuery.newFloatRange("price", 55f, 60f, true,false);// 組合關(guān)系代表的意思如下:// 1、MUST和MUST表示“與”的關(guān)系,即“交集”。// 2、MUST和MUST_NOT前者包含后者不包含。// 3、MUST_NOT和MUST_NOT沒意義// 4、SHOULD與MUST表示MUST,SHOULD失去意義;// 5、SHOUlD與MUST_NOT相當(dāng)于MUST與MUST_NOT。// 6、SHOULD與SHOULD表示“或”的概念。 query.add(q1, Occur.MUST_NOT);query.add(q2, Occur.MUST_NOT);doSearch(query);}@Testpublic void multiFieldQueryParser() throws Exception {// 創(chuàng)建7.3.2 MultiFieldQueryParser// 默認(rèn)搜索的多個(gè)域的域名String[] fields = { "name", "description" };Analyzer analyzer = new StandardAnalyzer();Map<String, Float> boosts = new HashMap<String, Float>();boosts.put("name", 200f);MultiFieldQueryParser parser = new MultiFieldQueryParser(fields,analyzer, boosts);// Query query = parser.parse("name:lucene OR description:lucene");Query query = parser.parse("java");System.out.println(query);doSearch(query);} } View Code

    QueryParser實(shí)現(xiàn):

package com.itheima.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.index.IndexReader; 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.ScoreDoc; import org.apache.lucene.search.TopDocs; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory;import java.io.IOException; import java.nio.file.Paths;/*** Lucene的搜索功能* 作者: Administrator* 日期: 2017/9/6**/ public class LuceneSearch {public static void main(String[] args) throws ParseException, IOException {// 使用QueryParser 參數(shù)分別為默認(rèn)搜索域與分詞器String f = "description";Analyzer a = new StandardAnalyzer();QueryParser parser = new QueryParser(f, a);// 通過parser創(chuàng)建Query對象String q = "description:java"; // 查詢語句(Luncene語法)Query query = parser.parse(q);// 創(chuàng)建IndexSearcherString path = "D:\\BdiduYunDownload\\lucene\\index";Directory dir = FSDirectory.open(Paths.get(path));IndexReader reader = DirectoryReader.open(dir);IndexSearcher searcher = new IndexSearcher(reader);// 通過searcher搜索,分別為查詢對象和需要顯示的條數(shù)TopDocs topDocs = searcher.search(query, 10);// 結(jié)果處理int totalHits = topDocs.totalHits; // 總記錄數(shù)System.out.println("總記錄數(shù):"+totalHits);ScoreDoc[] scoreDocs = topDocs.scoreDocs; // 經(jīng)過打分的文檔for (ScoreDoc scoreDoc : scoreDocs) {// 獲取doc的IDint docID = scoreDoc.doc;// 根據(jù)docID獲取文檔(類似數(shù)據(jù)庫的一條記錄)Document doc = searcher.doc(docID);System.out.println("ID為:"+doc.get("id"));System.out.println("name為:"+doc.get("name"));System.out.println("price為:"+doc.get("price"));System.out.println("pic為:"+doc.get("pic"));System.out.println("description為:"+doc.get("description"));}// 關(guān)閉reader reader.close();} } View Code

    結(jié)果:

    

?  關(guān)于Lucene的更多詳細(xì)介紹,請參見 xingoo 的隨筆:http://www.cnblogs.com/xing901022/p/3933675.html

轉(zhuǎn)載于:https://www.cnblogs.com/jiangbei/p/7482249.html

總結(jié)

以上是生活随笔為你收集整理的Lucene第一讲——概述与入门的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。