[lucene系列筆記2]在eclipse里初步使用lucene的索引和查詢功能


首先,new一個java project,名字叫做LuceneTools。

然后,在project里new一個class,名字叫做IndexFiles。這個類用來給文件建索引(建好索引以后就可以高效檢索了)。

在寫代碼之前,我們要先引入一下lucene包,就類似於C語言里的include。如圖:

點擊之后看到如下窗口,選擇“Add External JARs”

然后找到C:\Lucene-6.2.1目錄下(如果是按上一篇文章配置的話應該是在這個目錄里)的三個包(這里我們暫時只用到這三個包)引入工程里。之后工程大概是這個模樣:

對於中文來說analyzer用smartcn那一個更好,就是除了導入analyzers-common,再導入一個analyzers-smartcn,然后代碼里的StandardAnalyzer()都換成SmartChineseAnalyzer()就可以了。

 

下面我們就可以來寫代碼了。

 

打開IndexFiles.java文件,這里我們假設要對D:\lucenetest\files文件夾建立索引,而且,而且我們假設這個目錄下只有文件而沒有文件夾(為了讓代碼更簡單),然后建立好的索引保存在D:\lucenetest\index目錄下。

那么我們寫入如下代碼:

import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.*;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
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.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

/**
 * @author song
 * @description: 
 * 依賴jar:Lucene-core,lucene-analyzers-common,lucene-queryparser
 * 作用:簡單的索引建立
 */
public class IndexFiles {
    public static Version luceneVersion = Version.LATEST;
    /**
     * 建立索引
     */
    public static void createIndex(){
        IndexWriter writer = null;
        try{
            //1、創建Directory
            //Directory directory = new RAMDirectory();//創建內存directory
            Directory directory = FSDirectory.open(Paths.get("D:/lucenetest/index"));//在硬盤上生成Directory00
            //2、創建IndexWriter
            IndexWriterConfig iwConfig = new IndexWriterConfig( new StandardAnalyzer());
            writer = new IndexWriter(directory, iwConfig);
            //3、創建document對象
            Document document = null;
            //4、為document添加field對象
            File f = new File("D:/lucenetest/files");//索引源文件位置
            for (File file:f.listFiles()){
                    document = new Document();
                    document.add(new StringField("path", f.getName(),Field.Store.YES));
                    System.out.println(file.getName());
                    document.add(new StringField("name", file.getName(),Field.Store.YES));
                    InputStream stream = Files.newInputStream(Paths.get(file.toString()));
                    document.add(new TextField("content", new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8))));//textField內容會進行分詞
                    //document.add(new TextField("content", new FileReader(file)));  如果不用utf-8編碼的話直接用這個就可以了
                    writer.addDocument(document);
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            //6、使用完成后需要將writer進行關閉
            try {
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    public static void main(String[] args) throws IOException
    {
        createIndex();
    }
}

 

在運行之前我們先在D:\lucenetest\files文件夾下創建幾個txt,比如第一個文件命名為hello.txt,第二個文件命名為test.txt。然后在里面隨便寫點什么內容。這里要注意的是,上面的代碼是針對中文搜索的問題使用了utf-8編碼,所以要求文件也是utf-8的編碼。如圖:

然后運行IndexFiles.java。會看到索引建立完成。D:\lucenetest目錄下多了一個index文件夾。

 

下面我們就要用這個index來檢索了。

new一個class,命名為SearchFiles。然后在里面寫入如下代碼:

import java.nio.file.Paths;
import java.io.*;

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.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 org.apache.lucene.util.Version;

/**
 * @author song
 * @description: 
 * 依賴jar:Lucene-core,lucene-analyzers-common,lucene-queryparser
 * 作用:使用索引搜索文件
 */
public class SearchFiles {
    public static Version luceneVersion = Version.LATEST;
    /**
     * 查詢內容
     */
    public static String indexSearch(String keywords){
        String res = "";
        DirectoryReader reader = null;
        try{
//            1、創建Directory
             Directory directory = FSDirectory.open(Paths.get("D:/lucenetest/index"));//在硬盤上生成Directory
//            2、創建IndexReader
             reader = DirectoryReader.open(directory);
//            3、根據IndexWriter創建IndexSearcher
             IndexSearcher searcher =  new IndexSearcher(reader);
//            4、創建搜索的query
//            創建parse用來確定搜索的內容,第二個參數表示搜索的域
             QueryParser parser = new QueryParser("content",new StandardAnalyzer());//content表示搜索的域或者說字段
             Query query = parser.parse(keywords);//被搜索的內容
//            5、根據Searcher返回TopDocs
             TopDocs tds = searcher.search(query, 20);//查詢20條記錄
//            6、根據TopDocs獲取ScoreDoc
             ScoreDoc[] sds = tds.scoreDocs;
//            7、根據Searcher和ScoreDoc獲取搜索到的document對象
             int cou=0;
             for(ScoreDoc sd:sds){
                 cou++;
                 Document d = searcher.doc(sd.doc);
//                    8、根據document對象獲取查詢的字段值
                 /**  查詢結果中content為空,是因為索引中沒有存儲content的內容,需要根據索引path和name從原文件中獲取content**/
                 res+=cou+". "+d.get("path")+" "+d.get("name")+" "+d.get("content")+"\n";
             }

            
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            //9、關閉reader
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return res;
    }
    public static void main(String[] args) throws IOException
    {
        System.out.println(indexSearch("你好")); //搜索的內容可以修改
    }
}

 

運行就會看到,搜索出了nihao.txt這個文件

 

 

至此,我們已經學會了簡單的建立索引和搜索了~~~


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM