Lucener认识

来源:互联网 发布:商城源码单用户版 编辑:程序博客网 时间:2024/06/14 09:50

Lucene认识

使用Maven创建项目

拷贝Maven依赖

http://mvnrepository.com/

<dependencies>    <dependency>        <groupId>org.apache.lucene</groupId>        <artifactId>lucene-core</artifactId>        <version>5.3.1</version>    </dependency>    <dependency>        <groupId>org.apache.lucene</groupId>        <artifactId>lucene-queryparser</artifactId>        <version>5.3.1</version>    </dependency>    <dependency>        <groupId>org.apache.lucene</groupId>        <artifactId>lucene-analyzers-common</artifactId>        <version>5.3.1</version>    </dependency></dependencies>

检索有一个索引,首先要构建索引在E:\software\lucene目录下,将数据文件放入

对数据文件进行检索

Indexer.java

package com.matrix.lucene;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    // indexDir:将索引写入到索引目录(该目录存放创建的索引文件)去    public Indexer(String indexDir) throws Exception {        Directory dir = FSDirectory.open(Paths.get(indexDir));        // 创建标准分词器        Analyzer analyzer = new StandardAnalyzer();        // 配置,传入分析器实例        // 要将索引写入到数据源目录下文件中的时候需要解析/分析        IndexWriterConfig wc = new IndexWriterConfig(analyzer);        writer = new IndexWriter(dir, wc);    }    // 关闭写索引    public void close() throws Exception {        writer.close();    }    // 遍历数据源目录    // 索引数据源目录的所有文件    public int index(String dataDir) throws Exception {        File[] files = new File(dataDir).listFiles();        // 得到数据源目录下的每个文件        for (File f : files) {            indexFile(f);        }        // 返回所有的索引文件        return writer.numDocs();    }    // 对数据源目录下每个文件进行索引/索引指定文件    private void indexFile(File f) throws Exception {        // 一行就是一个Document,Document里面还有一个个Field        System.out.println("索引文件:" + f.getCanonicalPath());        // 索引的目的是为了搜索,索引前要对搜索的内容创建成Document和Field。        Document doc = getDocument(f);        // 添加索引到文件中        writer.addDocument(doc);    }    // 获取文档,文档里再设置每个字段    private Document getDocument(File f) throws Exception {        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;    }    // main方法,测试    public static void main(String[] args) {        // 创建索引目录 ,该目录存放创建的索引文件        String indexDir = "E:\\software\\lucene\\demo";        // 创建数据源目录,该目录存放要搜索的原始文件        String dataDir = "E:\\software\\lucene\\data";        // 实例化Indexer        Indexer indexer = null;        int numIndexed = 0;        // 为了查看程序执行的效率,计时        long start = System.currentTimeMillis();        try {            indexer = new Indexer(indexDir);            numIndexed = indexer.index(dataDir);        } catch (Exception e) {            e.printStackTrace();        } finally {            try {                indexer.close();            } catch (Exception e) {                // TODO Auto-generated catch block                e.printStackTrace();            }        }        long end = System.currentTimeMillis();        // 数据索引        System.out.println("索引:" + numIndexed + "个文件,花费了" + (start - end) + "毫秒");    }}

生成的文件

对文件内容进行搜索

Searcher.java

package com.matrix.lucene;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.index.DirectoryReader;import org.apache.lucene.index.IndexReader;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;/** * 查询 *  * Searcher<BR> * 创建人:Matrix <BR> * 时间:2016年4月25日-下午7:42:01 <BR> *  * @version 1.0.0 * */public class Searcher {    /**     *      * 描述:查询索引<BR>     * 方法名:search<BR>     * 创建人:Matrix <BR>     * 时间:2016年4月25日-下午7:45:33 <BR>     *      * @param indexDir     *            查询的目录     * @param q     *            查询的字段     * @throws Exception     *             void<BR>     * @exception <BR>     * @see     * @since 1.0.0     */    public static void search(String indexDir, String q) throws Exception {        //        Directory dir = FSDirectory.open(Paths.get(indexDir));        // 读取完整目录下的索引        IndexReader reader = DirectoryReader.open(dir);        // 索引查询器        IndexSearcher is = new IndexSearcher(reader);        // 标准分词器        Analyzer analyzer = new StandardAnalyzer();        QueryParser parser = new QueryParser("contents", analyzer);        // 解析        Query query = parser.parse(q);        long start = System.currentTimeMillis();        // 查询前10个        TopDocs hits = is.search(query, 10);        long end = System.currentTimeMillis();        System.out.println("匹配:" + q + ",总共花费" + (end - start) + "毫秒" + "查询到" + hits.totalHits + "个记录");        // 遍历TopDocs        for (ScoreDoc scoreDoc : hits.scoreDocs) {            Document doc = is.doc(scoreDoc.doc);            System.out.println(doc.get("fullPath"));        }        reader.close();    }    public static void main(String[] args) {        // 创建索引目录 ,该目录存放创建的索引文件        String indexDir = "E:\\software\\lucene\\demo";        // 查询条件        String q = "Java";        try {            search(indexDir, q);        } catch (Exception e) {            e.printStackTrace();        }    }}

0 0
原创粉丝点击