標籤:高效 .text top 源檔案位置 amd clip set 檔案中 final
首先,new一個java project,名字叫做LuceneTools。
然後,在project裡new一個class,名字叫做IndexFiles。這個類用來給檔案建索引(建好索引以後就可以高效檢索了)。
在寫代碼之前,我們要先引入一下lucene包,就類似於C語言裡的include。
點擊之後看到如下視窗,選擇“Add External JARs”
然後找到C:\Lucene-6.2.1目錄下(如果是按上一篇文章配置的話應該是在這個目錄裡)的三個包(這裡我們暫時只用到這三個包)引入工程裡。之後工程大概是這個模樣:
下面我們就可以來寫代碼了。
開啟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這個檔案
至此,我們已經學會了簡單的建立索引和搜尋了~~~
[lucene系列筆記2]在eclipse裡初步使用lucene的索引和查詢功能