Lucene(01)

来源:http://www.cnblogs.com/tenglongwentian/archive/2016/10/29/6011263.html
-Advertisement-
Play Games

我的博客園博文地址:http://www.cnblogs.com/tenglongwentian/ Lucene,最新版是Lucene6.2.1,匹配的jdk版本是1.8正式版。這裡用jdk7最後一版,所以用Lucene5.3.3。 新建一個maven項目,如果不會可以參考前面的博文,前面的博文有專 ...


我的博客園博文地址:http://www.cnblogs.com/tenglongwentian/

Lucene,最新版是Lucene6.2.1,匹配的jdk版本是1.8正式版。
這裡用jdk7最後一版,所以用Lucene5.3.3。

新建一個maven項目,如果不會可以參考前面的博文,前面的博文有專門提到如何新建maven項目。
新建的maven項目:<packaging>jar</packaging>,

 1 <dependencies>
 2         <!-- https://mvnrepository.com/artifact/org.apache.lucene/lucene-core -->
 3         <dependency>
 4             <groupId>org.apache.lucene</groupId>
 5             <artifactId>lucene-core</artifactId>
 6             <version>5.5.3</version>
 7         </dependency>
 8         <!-- https://mvnrepository.com/artifact/org.apache.lucene/lucene-queryparser -->
 9         <dependency>
10             <groupId>org.apache.lucene</groupId>
11             <artifactId>lucene-queryparser</artifactId>
12             <version>5.5.3</version>
13         </dependency>
14         <!-- https://mvnrepository.com/artifact/org.apache.lucene/lucene-analyzers-common -->
15         <dependency>
16             <groupId>org.apache.lucene</groupId>
17             <artifactId>lucene-analyzers-common</artifactId>
18             <version>5.5.3</version>
19         </dependency>
20     </dependencies>

因為我用jdk7,不喜歡每次更新maven倉庫都要手動調整項目的jdk版本,所以

 1 <!-- 源碼目錄,插件管理等配置 -->
 2     <build>
 3         <finalName>Lucene</finalName>
 4         <plugins>
 5             <plugin>
 6                 <groupId>org.apache.maven.plugins</groupId>
 7                 <artifactId>maven-compiler-plugin</artifactId>
 8                 <version>3.3</version>
 9                 <configuration>
10                     <!-- 指定source和target的版本 -->
11                     <!-- source 指定用哪個版本的編譯器對java源碼進行編譯 -->
12                     <source>1.7</source>
13                     <!-- target 指定生成的class文件將保證和哪個版本的虛擬機進行相容 -->
14                     <target>1.7</target>
15                 </configuration>
16             </plugin>
17         </plugins>
18     </build>

可以這樣。

新建兩個類:

Indexer

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();// 標準分詞器
        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 {
        // TODO Auto-generated method stub
        System.out.println("索引文件:" + f.getCanonicalFile());
        Document doc = getDocument(f);
        writer.addDocument(doc);
    }

    /**
     * 獲取文檔,文檔里在設置每個欄位
     * 
     * @param f
     * @return
     * @throws Exception
     */
    private Document getDocument(File f) throws Exception {
        // TODO Auto-generated method stub
        Document doc = new Document();
        doc.add(new TextField("contents", new FileReader(f)));
        doc.add(new TextField("fileName", f.getName(), Field.Store.YES));
        doc.add(new TextField("fullPath", f.getCanonicalPath(), Field.Store.YES));
        return doc;
    }
    public static void main(String[] args){
        String indexDir="E:\\lucene";
        String dataDir="E:\\lucene\\data";
        Indexer indexer = null;
        int numIndexed=0;
        long start=System.currentTimeMillis();
        try {
            indexer = new Indexer(indexDir);
            numIndexed=indexer.index(dataDir);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            try {
                indexer.close();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        long end=System.currentTimeMillis();
        System.out.println("索引:"+numIndexed+"個文件,花費了"+(end-start)+"毫秒");
    }
}
String indexDir="E:\\lucene";
String dataDir="E:\\lucene\\data";
看到這裡不要好奇,盤符隨意,在任意盤符根目錄下新建文件夾,最好英文無空格,中文未測試,然後拷貝幾個txt文件到data文件夾下麵,一會測試用的到。
然後運行這個類,可以看到


然後可以在lucene文件夾下看到這幾個奇怪的文件,是什麼後面會提到,稍安勿躁。

新建另一個類:

Searcher

 1 import java.nio.file.Paths;
 2 
 3 import org.apache.lucene.analysis.Analyzer;
 4 import org.apache.lucene.analysis.standard.StandardAnalyzer;
 5 import org.apache.lucene.document.Document;
 6 import org.apache.lucene.index.DirectoryReader;
 7 import org.apache.lucene.index.IndexReader;
 8 import org.apache.lucene.queryparser.classic.QueryParser;
 9 import org.apache.lucene.search.IndexSearcher;
10 import org.apache.lucene.search.Query;
11 import org.apache.lucene.search.ScoreDoc;
12 import org.apache.lucene.search.TopDocs;
13 import org.apache.lucene.store.Directory;
14 import org.apache.lucene.store.FSDirectory;
15 
16 public class Searcher {
17     public static void search(String indexDir, String q) throws Exception {
18         Directory dir = FSDirectory.open(Paths.get(indexDir));
19         IndexReader reader = DirectoryReader.open(dir);
20         IndexSearcher is = new IndexSearcher(reader);
21         Analyzer analyzer = new StandardAnalyzer();
22         QueryParser parse = new QueryParser("contents", analyzer);
23         Query query = parse.parse(q);
24         long start = System.currentTimeMillis();
25         TopDocs hits = is.search(query, 10);
26         long end = System.currentTimeMillis();
27         System.out.println("匹配" + q + ",總共花費" + (end - start) + "毫秒," + "查詢到" + hits.totalHits + "個記錄");
28         for (ScoreDoc scoreDoc : hits.scoreDocs) {
29             Document doc = is.doc(scoreDoc.doc);
30             System.out.println(doc.get("fullPath"));
31         }
32         reader.close();
33     }
34 
35     public static void main(String[] args) {
36         String indexDir = "E:\\lucene";
37         //String q = "LICENSE-2.0";
38         String q = "Zygmunt Saloni";
39         try {
40             search(indexDir, q);
41         } catch (Exception e) {
42             // TODO Auto-generated catch block
43             e.printStackTrace();
44         }
45     }
46 }

運行這個類,

不要把第一個類生成的幾個特殊的文件刪除,任性的話,試試看,會報錯,如果刪除運行第一個類生成的幾個特殊的奇怪文件後再運行第二個類的時候會報錯。

還是任性的試試看吧。

對比String q = "Zygmunt Saloni";事實證明沒什麼影響,因為分詞了,整體切割。

加上-運行第二個類的話,結果一樣,自己試試看。

轉載請註明出處,謝謝。


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 本文所討論的網路埠復用並非指網路編程中採用SO_REUSEADDR選項的 Socket Bind 復用。它更像是一個帶特定路由功能的埠轉發工具,在應用層實現。可以在80埠上復用一個SSH服務。 ...
  • 讀程式,輸出結果:1(finally的return覆蓋了catch的return) 讀程式,輸出結果:編譯錯誤(17行使用了未初始化的變數) ...
  • strlen(p): 能計算出p指向字元串的長度(以當前p的位置開始),不包含終止字元'\0'; p可以聲明為char* p或者char p[],這兩種形式strlen均能正確計算。 sizeof(p): sizeof是一個操作符,非函數,其值在編譯期確定,因此當p聲明為某一類型指針時,sizeof ...
  • 大家好,今天帶來的是自己實現的用C++完成基數排序.在數據結構,演算法分析和程式設計的學習過程中,我們經常也無法避免的要學到排序的演算法.排序演算法是程式設計過程中使用頻率極高的演算法之一,其輸入是一組無序的序列,要求以升序或者降序的方式輸出一組有序的序列.對於如二分查找等演算法,要求輸入是有序的序列,也就是 ...
  • 很多同學對於overload和override傻傻分不清楚,建議不要死記硬背概念性的知識,要理解著去記憶。 先給出我的定義: overload(重載):在同一類或者有著繼承關係的類中,一組名稱相同,參數不同的方法組。本質是對不同方法的稱呼。 override(覆寫):存在繼承關係的兩個類之間,在子類 ...
  • 標記名稱:flink [標簽簡介] [功能說明]:用於獲取友情鏈接,其對應後臺文件為"includetaglibflink.lib.php". [適用範圍]:全局標記,適用V55,V56,V57。 [參數說明]: [1]type:鏈接類型,值: a. textall 全部用文字顯示; b. text ...
  • // 首碼形式:增加然後取回值UPInt& UPInt::operator++(){ *this += 1; // 增加 return *this; // 取回值}// postfix form: fetch and incrementconst UPInt UPInt::operator++(in ...
  • 如下記錄一次作業: 很顯然,我這個應該屬於二逼青年版,會在以後更新文藝青年版的答案。 1、模仿sed,一個文件中,用新字元串替換老字元串。 2、查找、添加、刪除特定的內容 ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...