1. 程式人生 > >30分鐘,快速上手Lucene v7.4.0

30分鐘,快速上手Lucene v7.4.0

Lucene截止目前,最新版本為v7.4.0。它是一個開放原始碼的全文檢索引擎工具包,但它不是一個完整的全文檢索引擎,而是一個全文檢索引擎的架構,提供了完整的查詢引擎和索引引擎,部分文字分析引擎(英文與德文兩種西方語言)。

目錄:

1 Lucene環境相關

$ uname -a

Linux ubuntu 4.15.0-32-generic #35-Ubuntu SMP Fri Aug 10 17:58:07 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux

$ java -version

java version “1.8.0_181”
Java(TM) SE Runtime Environment (build 1.8.0_181-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.181-b13, mixed mode)

補充:對應的安裝包名稱為jdk-8u181-linux-x64.tar.gz,Ubuntu 18.04.1 LTS,MyEclipse CI 2018.8.0

2 Add External JARs…(右擊專案->Build Path)

3 配置git

$ sudo apt install git
$ git config --global user.name "qingdujun"
$ git config --global user.email "[email protected]"
$ ssh-keygen -t rsa -C "[email protected]
"

Generating public/private rsa key pair.
Enter file in which to save the key (/home/qingdujun/.ssh/id_rsa):
Created directory ‘/home/qingdujun/.ssh’.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/qingdujun/.ssh/id_rsa.
Your public key has been saved in /home/qingdujun/.ssh/id_rsa.pub.

$ vim /home/qingdujun/.ssh/id_rsa.pub

拷貝里面的內容至github.com->settings->SSH and GPG keys->New SSH key

4 Lucene v7.4.0 source code

git clone https://github.com/qingdujun/LuceneRes/releases/tag/v0.1

4.1 索引目錄

~/Documents/LuceneRes/Index$ ls

_0.cfe _0.cfs _0.si segments_2 write.lock

4.2 執行結果

Console
Indexing /home/qingdujun/Documents/LuceneRes/Data/LuceneConstants.java
Indexing /home/qingdujun/Documents/LuceneRes/Data/Searcher.java
Indexing /home/qingdujun/Documents/LuceneRes/Data/LuceneTester.java
Indexing /home/qingdujun/Documents/LuceneRes/Data/TextFileFilter.java
Indexing /home/qingdujun/Documents/LuceneRes/Data/Indexer.java
5 File indexed, time taken: 128 ms
3 documents found. Time: 40 ms
File: /home/qingdujun/Documents/LuceneRes/Data/Indexer.java
File: /home/qingdujun/Documents/LuceneRes/Data/Searcher.java
File: /home/qingdujun/Documents/LuceneRes/Data/LuceneTester.java

5 附錄(可執行原始碼):

5.1 TextFileFilter.java

package com.cfs.lucene;

import java.io.File;
import java.io.FileFilter;

public class TextFileFilter implements FileFilter{
    public static final String TEXT_TYPE = ".java";

    @Override
    public boolean accept(File pathname) {
        return pathname.getName().toLowerCase().endsWith(TEXT_TYPE);
    }
}

5.2 LuceneConstants.java

package com.cfs.lucene;

public class LuceneConstants {
    public static final String CONTENTS = "contents";
    public static final String FILE_NAME = "filename";
    public static final String FILE_PATH = "filepath";
    public static final int MAX_SEARCH = 10;
}

5.3 Indexer.java

package com.cfs.lucene;

import java.io.File;
import java.io.FileFilter;
import java.io.FileReader;
import java.io.IOException;
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.Field.Store;
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;

public class Indexer {

    private IndexWriter indexWriter = null;
    /**
     * Construct index
     * @param directoryPath The directory where the index is located
     * @throws IOException
     */
    public Indexer(String directoryPath) throws IOException{
        Directory directory = FSDirectory.open(Paths.get(directoryPath));
        Analyzer analyzer = new StandardAnalyzer();
        IndexWriterConfig indexWriterConfig = new IndexWriterConfig(analyzer);
        indexWriter = new IndexWriter (directory, indexWriterConfig);
    }
    /**
     * Close write index
     * @throws IOException
     */
    public void close() throws IOException{
        indexWriter.close();
    }
    /**
     * Convert a file to an index object(document)
     * @param file
     * @return
     * @throws IOException
     */
    private Document getDocument(File file) throws IOException{
        Document document = new Document();
        //TextField, A field that is indexed and tokenized
        Field contentsField = new TextField(LuceneConstants.CONTENTS, new FileReader(file));
        document.add(contentsField);
        //StringField, A field that is indexed but not tokenized
        Field fileNameField = new StringField(LuceneConstants.FILE_NAME, file.getName(),Store.YES);
        document.add(fileNameField);
        Field filePathField = new StringField(LuceneConstants.FILE_PATH, file.getCanonicalPath(), Store.YES);
        document.add(filePathField);
        return document;
    }
    /**
     * Index file
     * @param file
     * @throws IOException
     */
    private void indexFile(File file) throws IOException{
        System.out.println("Indexing "+file.getCanonicalPath());
        Document document = getDocument(file);
        indexWriter.addDocument(document);
    }
    /**
     * Index all files
     * @param dataDirPath Indexed data storage directory
     * @param fileFilter
     * @return
     * @throws IOException
     */
    public int createIndex(String dataDirPath, FileFilter fileFilter) throws IOException{
        File[] files = new File(dataDirPath).listFiles();
        for (File file : files) {
            if (!file.isDirectory() && !file.isHidden() && file.exists() 
                    && file.canRead() && fileFilter.accept(file)) {
                indexFile(file);
            }
        }
        return indexWriter.numDocs();
    }

    /**
     * Read the entire contents of the file and return the bytes
     * @param file
     * @return
     * @throws IOException
     */
//  private byte[] read2Bytes(File file) throws IOException {
//      Long fileLength = file.length();
//      byte[] contents = new byte[fileLength.intValue()];
//      FileInputStream fileInputStream = new FileInputStream(file);
//      fileInputStream.read(contents);
//      fileInputStream.close();
//      return contents;
//  } 
//  

5.4 Searcher.java

package com.cfs.lucene;

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

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.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;

public class Searcher {
    IndexSearcher indexSearcher = null;
    QueryParser queryParser = null;
    Query query = null;
    Directory directory = null;
    DirectoryReader directoryReader = null;

    public Searcher(String directoryPath) throws IOException{
        //Store the index in memory
        //Directory directory = new RAMDirectory();
        //Store an index on disk
        directory = FSDirectory.open(Paths.get(directoryPath));
        directoryReader = DirectoryReader.open(directory);
        indexSearcher = new IndexSearcher(directoryReader);
        queryParser = new QueryParser(LuceneConstants.CONTENTS, new StandardAnalyzer());
    }

    public TopDocs search(String searchQuery) throws ParseException, IOException {
        query = queryParser.parse(searchQuery);
        return indexSearcher.search(query, LuceneConstants.MAX_SEARCH);
    }

    public Document getDocument(ScoreDoc scoreDoc) throws IOException {
        return indexSearcher.doc(scoreDoc.doc);
    }

    public void close() throws IOException {
        directoryReader.close();
        directory.close();
    }
}

5.5 LuceneTester.java

package com.cfs.lucene;

import java.io.IOException;

import org.apache.lucene.document.Document;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;

public class LuceneTester {
    /*
     *basePath Need to be modified to your root dorectory 
     */
    public static final String basePath = "/home/qingdujun/Documents/LuceneRes/";
    public static final String indexDir = basePath+"Index";
    public static final String dataDir = basePath+"Data";

    private Indexer indexer = null;
    private Searcher searcher = null;
    /**
     * Test the function of create index
     * @throws IOException
     */
    private void createIndex() throws IOException {
        indexer = new Indexer(indexDir);
        int numIndexed = 0;
        long startTime = System.currentTimeMillis();
        numIndexed = indexer.createIndex(dataDir, new TextFileFilter());
        long endTime = System.currentTimeMillis();
        indexer.close();
        System.out.println(numIndexed+" File indexed, time taken: "+(endTime-startTime)+" ms");
    }
    /**
     * Test the function of search result
     * @param searchQuery What you want to search for
     * @throws IOException
     * @throws ParseException
     */
    private void search(String searchQuery) throws IOException, ParseException {
        searcher = new Searcher(indexDir);
        long startTime = System.currentTimeMillis();
        TopDocs hits = searcher.search(searchQuery);
        long endTime = System.currentTimeMillis();
        System.out.println(hits.totalHits+" documents found. Time: "+(endTime-startTime)+" ms");
        for (ScoreDoc scoreDoc : hits.scoreDocs) {
            Document document = searcher.getDocument(scoreDoc);
            System.out.println("File: "+document.get(LuceneConstants.FILE_PATH));
        }
        searcher.close();
    }

    public static void main(String[] args) {
        LuceneTester luceneTester = new LuceneTester();
        try {
            luceneTester.createIndex();
            luceneTester.search("throws IOException");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

©qingdujun
2018-8-30 於 北京 海淀

相關推薦

30分鐘快速上手Lucene v7.4.0

Lucene截止目前,最新版本為v7.4.0。它是一個開放原始碼的全文檢索引擎工具包,但它不是一個完整的全文檢索引擎,而是一個全文檢索引擎的架構,提供了完整的查詢引擎和索引引擎,部分文字分析引擎(英文與德文兩種西方語言)。 目錄: 1 Luce

學習Git---20分鐘git快速上手

diff 是什麽 學習 改變世界 ren ont 其中 網線 復雜 學習Git-----20分鐘git快速上手 (圖片已修復)在Git如日中天的今天,不懂git都不好意思跟人說自己是程序猿。你是不是早就躍躍欲試了,只是苦於沒有借口(契機)。 好吧,機會就在今

Laravel入門及實踐快速上手社交系統ThinkSNS+二次開發

title 瀏覽器 extend 成了 migration 如果 編寫 三種 views 【摘要】自從社交系統ThinkSNS+不使用ThinkPHP框架而使用Laravel框架之後,很多人都說技術門檻擡高了,其實你與TS+的距離僅僅只是學習一個新框架而已,所以,我們今天來

JUnit 5 快速上手(從 JUnit 4 到 JUnit 5)

sina doc href tar style http gin weibo targe 我從治中緞擁徹仿褂陌耘http://weibo.com/u/5849150516 戮禾等搶講幌撂淖漢敖http://weibo.com/u/5848927851 坷屏蹬慚蕾覓尚簿馱

從零開始學 Web 之 Ajax(三)Ajax 概述快速上手

lan 技術分享 php 概述 由於 val asc logs 更新 大家好,這裏是「 從零開始學 Web 系列教程 」,並在下列地址同步更新...... github:https://github.com/Daotin/Web 微信公眾號:Web前端之巔 博客園:ht

UNIPAY.AI--系統商30分鐘即可快速接入聚合支付

系統商接入聚合支付痛點,開發、對接、設計成本等因素,決定了傳統系統商接入移動支付的門檻很高。 具體如下: 1、開發成本高 交易系統開發涉及支付介面、訂單、賬務系統等多個模組,開發投入大、門檻高,且後期需要開發團隊不斷進行維護升級。 2、支付通道多,對接難 直連通道安全穩定,缺少專業的服務商與

不懂Git,別說自己是程式猿–20分鐘git快速上手

原連結: http://www.makeyuan.com/2014/01/28/886.html 在Git如日中天的今天,不懂git都不好意思跟人說自己是程式猿。你是不是早就躍躍欲試了,只是苦於沒有藉口(契機)。 好吧,機會就在今天。 給我20分鐘,是的,只要20分鐘

充分理解Kotlin快速上手寫業務

前言 即使每天10點下班,其實需求很多,我也要用這腐朽的聲帶喊出:我要學習,我要寫文章!! 又是一篇Kotlin的文章,為啥...還不是因為工作需要。毫無疑問,最好的學習方式是通過官方文件去學習。不過個人覺得官方文件多多少少有一些不夠高效。 中文官方文件 因此這篇是從我學習

如何把照片做成視訊?抖音爆款的圖片視訊切換教程快速上手

現在都流行用照片隨手記錄生活。而把照片做成視訊,又是現在刷爆抖音、朋友圈的形式。不僅有酷炫的圖片切換效果,還帶有動聽的背景音樂,這樣精美又吸睛的照片視訊,肯定能讓你獲得超多贊。今天就教大家用數碼大師快速把照片做成視訊,即刻擁有超酷炫超流行的效果。 一鍵運用上數碼大師中各種好看的照片切換特效

Solidity 語言簡易入門快速上手

Solidity語言簡介 solidity語言是一種可以編寫智慧合約的高階語言,當然編寫智慧合約不止這一種,但是學習以太坊最好還是學會這一種語言就差不多了。在以太坊平臺上,solidiy編寫的智慧合約會執行在以太坊虛擬機器EVM之上,變成位元組碼執行。 新手入門建議使用官方IDE開發工具Re

30分鐘--Spark快速入門指南

Apache Spark 是一個新興的大資料處理通用引擎,提供了分散式的記憶體抽象。Spark 正如其名,最大的特點就是快(Lightning-fast),可比 Hadoop MapReduce 的處理速度快 100 倍。此外,Spark 提供了簡單易用的 API,幾行程式碼就能實現 WordCount。本

RabbitMQ教程快速上手

1. 概述         RabbitMQ是資訊傳輸的中間者,本質上,從生產者接收訊息,轉達訊息給消費者。換句話說,就是根據你指定的規則進行訊息轉發,緩衝和持久化。         專業術語: &

今天第一次面試別人 大概聊了近30分鐘 呵呵。

       由於朋友臨時有事, 所以今天我代替一朋友進行一個電話面試, 第一次面試他人(不是應聘我們公司), 我以很認真負責的態度完成這個過程, 大概近30分鐘。 主要是技術面試, 在近30分鐘內, 我與被面試者是以交流學習的方式進行的, 整個溝通過程比較愉快。    

Fresco 的封裝快速上手影象後處理超大圖高清預覽縮小放大雙擊放大等一一俱全

因為某些原因,現在使用 jitpack.io,還請使用依賴的各位切換到 jitpack。在 project 下的 build.gradle 新增allprojects { repositories { ... maven { url 'https://jitpack.i

30分鐘學會經典小遊戲編程!

保存 ota 參考點 最大 編程 經典 通過 屬性 可能 在80後、90後的兒時記憶裏,俄羅斯方塊是必備的消遣小遊戲,它的玩法非常簡單基本大家都懂,但如何用編程語言開發一款兒時同款「俄羅斯方塊」,恐怕知道的同學就很少啦。 位置掩碼和旋轉掩碼 俄羅斯方塊遊戲中的格子一般是

OpenCV各版本差異與演化從1.x到4.0

部落格:blog.shinelee.me | 部落格園 | CSDN 寫在前面 最近因專案需要,得把OpenCV撿起來,登入OpenCV官網,竟然發現release了4.0.0-beata版本,所以藉此機會,查閱資料,瞭解下OpenCV各版本的差異及其演化過程,形成了以下幾點認識: 新版本的產生是

《linux裝置驅動開發》基於最新的linux 4.0核心-----筆記

第二章 Linux 的核心結構及構建 ---->這一章是自己總結的 1、核心結構(主要是下面這幾個部分) 系統呼叫介面<–>System call interface 程序管理<------>Process manag

修改和編譯spring原始碼構建jar(spring-context-4.0.2.RELEASE)

上週在定位問題的時候,發現有個異常是在spring構建bean的時候丟擲的,為了檢視更詳細的資訊,決定修改spring-context-4.0.2.RELEASE.jar中的CommonAnnotationBeanPostProcessor類的程式碼,在裡面打

保姆級教程——Ubuntu16.04 Server下深度學習環境搭建:安裝CUDA8.0cuDNN6.0Bazel0.5.4原始碼編譯安裝TensorFlow1.4.0(GPU版)

寫在前面 本文敘述了在Ubuntu16.04 Server下安裝CUDA8.0,cuDNN6.0以及原始碼編譯安裝TensorFlow1.4.0(GPU版)的親身經歷,包括遇到的問題及解決辦法,也有一些自己的經驗,希望能對讀者有所幫助。期間參考了許多前人的文章,後文會一一附上鍊接,在此先行謝過。在下能力有限,

VC6.0使用教程-30分鐘玩轉Microsoft Visual C++ 6.0

Visual C++ 6.0 簡稱VC或者VC6.0,是微軟推出的一款C和C++編譯器,具有強大的視覺化開發功能和除錯功能。VC6.0是使用最多的版本,非常經典,很多高校將VC6.0作為C語言的教學基礎,也是很多C語言入門學者的不二選擇。 學習C語言要多上機實驗、多程式設計