全文检索技术 lucene(001) 一个简单的Demo

本文介绍如何使用Lucene实现简单的全文检索系统。首先通过代码创建索引,然后演示了如何根据关键词查询索引并返回结果。

第一次接触全文检索,那就先来实现一个简单的demo

一、准备文本源和索引区

        要使用lucene进行全文检索,有以下几个步骤:1、针对文本源建立索引2、根据索引查询关键词。

        因此我们需要一个文本源和索引区。其中文本源是搜索的目标、索引区是lucene针对搜索目标所建立的索引区域。在此,我将我的文本源和索引区目录分别定义为:E:/study/dataE:/study/index。其中data中随意放置一些文本文档、index中为空即可。如下图

二、新建java工程,引入如下jar包。且新建两个类

两个类源码如下():

 

package com.sxt.lucene;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.TrueFileFilter;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.*;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.*;
import org.apache.lucene.util.Version;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.util.Collection;

/**
 * Created by ZhangJintao on 2017/7/15.
 */
public class CreateIndex {
    //索引文件夹
    public  static final String  indexDir="E:/study/index";
    //数据文件及
    public  static final String  dataDir="E:/study/data";

    @Test
    public void createIndex(){
        try{
            //定位到索引文件夹
            Directory dir = FSDirectory.open(new File(indexDir));
            //声明分词器。其中参数为lucene版本
            Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_4_9);
            //   声明索引Writer配置类,其中参数为lucene版本和分析器
            // (注:若检索文档中有汉字,则默认分词器则不适用,此处忽略掉汉子的影响)
            IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_4_9,analyzer);
            //给Writer配置写入类型,此处配置的为CREATE_OR_APPEND(创建或累加)
            config.setOpenMode(IndexWriterConfig.OpenMode.CREATE_OR_APPEND);
            //将  索引文件夹 和 索引writer写入配置作为构造函数的参数,声明索引writer类
            IndexWriter writer = new IndexWriter(dir,config);
            //定位到数据文件夹
            File file = new File(dataDir);
            //获取数据文件夹下所有文件的数组
            File[] files = file.listFiles();
            //开始遍历数据文件夹下每一个文档,为其创建索引
            for (File f : files){
                //声明文档类
                Document doc = new Document();
                //将数据文件的文件名作为“filename”参数写入文档类
                doc.add(new StringField("filename",f.getName(), Field.Store.YES));
                //将数据文件的文本内容作为“content”参数写入文档类
                doc.add(new TextField("content", FileUtils.readFileToString(f), Field.Store.YES));
                //将数据文件的最后一次修改时间作为“lastModify”参数写入文档类
                doc.add(new LongField("lastModify",f.lastModified(),Field.Store.YES));
                //使用索引writer价格文档类写入索引
                writer.addDocument(doc);
            }
            //关闭索引writer
            writer.close();
        }catch (IOException e){
            e.printStackTrace();
        }
    }

}

 

 

package com.sxt.lucene;

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

import java.io.File;
import java.io.IOException;

/**
 * Created by ZhangJintao on 2017/7/15.
 */
public class SearchIndex {
    //索引文件夹
    public  static final String  indexDir="E:/study/index";
    //数据文件及
    public  static final String  dataDir="E:/study/data";

    @Test
    public void search(){
        try {
            //定位到索引文件
            Directory dir = FSDirectory.open(new File(indexDir));
            //声明索引读取类
            IndexReader reader = DirectoryReader.open(dir);
            //声明索引查询类
            IndexSearcher searcher = new IndexSearcher(reader);
            //声明查询解析器
            QueryParser qp = new QueryParser(Version.LUCENE_4_9,"content",new StandardAnalyzer(Version.LUCENE_4_9));
            //使用查询解析器解析“java”,生成查询类
            Query query = qp.parse("java");
            //使用索引查询类对query进行查询,且查询前十条
            TopDocs search = searcher.search(query,10);
            //获取查询结果的数组
            ScoreDoc[] scoreDocs = search.scoreDocs;
            //遍历数组
            for (ScoreDoc sc : scoreDocs){
                System.out.println("====================================================");
                //获取查询到的位置索引
                int docId = sc.doc;
                //获取文档
                Document document = reader.document(docId);
                //获取文档内容
                document.get("content");
                System.out.println(document.get("content"));
            }
            //关闭索引读取类
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 

三、执行CreateIndex中createIndex()方法。

 

        执行完毕之后,前往E:/study/index文件夹下会发现多了一些特殊后缀的文件,这就是lucene针对data创建的索引。如下图:

四、执行SearchIndex中searchIndex()方法

   控制台会输入检索到的详细信息  

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值