1. 程式人生 > >Lucene筆記33-Lucene的擴充套件-使用Tika建立索引並進行搜尋

Lucene筆記33-Lucene的擴充套件-使用Tika建立索引並進行搜尋

一、使用Tika建立索引

之前建立索引的文件都是txt檔案,現在有了Tika,我們就可以將pdf,word,html等檔案,通過Tika提取出文字,之後建立索引,建立索引的寫法和之前大致相似。只需要將content域對應的值做一下處理,之前是FileReader來讀取,現在是使用Tika.parse()來獲取。

public void index(boolean update) {
    IndexWriter indexWriter = null;
    try {
        Directory directory = FSDirectory.open(new File("E:\\Lucene\\IndexLibrary"));
        indexWriter = new IndexWriter(directory, new IndexWriterConfig(Version.LUCENE_35, new IKAnalyzer()));
        if (update) {
            indexWriter.deleteAll();
        }
        File[] files = new File("E:\\Lucene\\SearchSource\\TikaSource").listFiles();
        for (File file : files) {
            // 通過Tika來儲存資料
            Document document = new Document();
            // 如果需要,可以放入Metadata資料
            Metadata metadata = new Metadata();
            document.add(new Field("content", new Tika().parse(file, metadata)));
            document.add(new Field("fileName", file.getName(), Field.Store.YES, Field.Index.NOT_ANALYZED));
            document.add(new Field("path", file.getAbsolutePath(), Field.Store.YES, Field.Index.NOT_ANALYZED));
            document.add(new NumericField("date", Field.Store.YES, true).setLongValue(file.lastModified()));
            document.add(new NumericField("size", Field.Store.YES, true).setIntValue((int) (file.length() / 1024)));
            indexWriter.addDocument(document);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (indexWriter != null) {
            try {
                indexWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

二、使用Tika進行搜尋

索引檔案都創建出來了,搜尋自然就很簡單了,和之前一樣,重心應該放在建立索引上,直接上程式碼吧。

public void search() {
    try {
        Directory directory = FSDirectory.open(new File("E:\\Lucene\\IndexLibrary"));
        IndexSearcher indexSearcher = new IndexSearcher(IndexReader.open(directory));
        TermQuery termQuery = new TermQuery(new Term("content", "必須"));
        TopDocs topDocs = indexSearcher.search(termQuery, 20);
        for (ScoreDoc scoreDoc : topDocs.scoreDocs) {
            Document document = indexSearcher.doc(scoreDoc.doc);
            System.out.println(document.get("fileName"));
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}