`
xiang37
  • 浏览: 414197 次
  • 性别: Icon_minigender_1
  • 来自: 南京
社区版块
存档分类
最新评论

Lucene4全文索引示例

 
阅读更多

Lucene4.2.1示例,之前也做过3.6的示例。3.6的分词需要使用IKAnalyzer或者其他的分词,对中文的支持可能才会更好,但是4.2为我们提供了SmartChineseAnalyzer这个中文分词器。

 

下面是一个简单的示例程序,分别对应增删改查:

 

package com.xiva.test.lucene;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.cn.smart.SmartChineseAnalyzer;
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.SimpleFSDirectory;
import org.apache.lucene.util.Version;

public class IvFileIndex
{

    private static List<File> fileList = new ArrayList<File>(1024);

    public static void listAllFile(File fileDir)
    {
        File[] files = fileDir.listFiles();
        for (File file : files)
        {
            if (file.isDirectory())
            {
                listAllFile(file);
            }
            else
            {
                fileList.add(file);
            }
        }
    }

    public static void main(String[] args) throws Exception
    {
        File fileDir = new File("F:\\WorkSpace");
        File indexDir = new File("F:\\WorkSpace\\EclipseProjects\\luceneIndex");

        Analyzer luceneAnalyzer = new SmartChineseAnalyzer(Version.LUCENE_42);

        IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_42, luceneAnalyzer);
        config.setOpenMode(org.apache.lucene.index.IndexWriterConfig.OpenMode.CREATE);

        Directory fsDir = new SimpleFSDirectory(indexDir);
        IndexWriter indexWriter = new IndexWriter(fsDir, config);

        listAllFile(fileDir);
        long startTime = new Date().getTime();

        indexWriter.deleteAll();

        // 增加document到索引去
        for (File txtFile : fileList)
        {
            if (txtFile.isFile() && txtFile.getName().endsWith(".java"))
            {
                System.out.println(txtFile.getName());
                FileInputStream fis = null;
                try
                {
                    fis = new FileInputStream(txtFile);
                }
                catch (FileNotFoundException fnfe)
                {
                    continue;
                }

                try
                {
                    Document document = new Document();
                    Field fieldPath = new StringField("path", txtFile.getPath(), Field.Store.YES);
                    Field fieldBody = new TextField("body", new BufferedReader(new InputStreamReader(fis, "GBK")));

                    document.add(fieldPath);
                    document.add(fieldBody);
                    indexWriter.addDocument(document);
                }
                finally
                {
                    fis.close();
                }

                System.out.println("被索引文件:" + txtFile.getCanonicalPath());
            }
        }

        // 对索引进行优化
        indexWriter.forceMerge(10);

        indexWriter.close();

        // 测试一下索引的时间
        long endTime = new Date().getTime();
        System.out.println("索引耗费时间:" + (endTime - startTime) + " 毫秒!");
    }

}

 

package com.xiva.test.lucene;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Date;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.cn.smart.SmartChineseAnalyzer;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.SimpleFSDirectory;
import org.apache.lucene.util.Version;

/**
 * 
 * 删除索引
 * @author xiva
 * @version [版本号, 2013-4-30]
 * @see [相关类/方法]
 * @since [产品、模块版本]
 */
public class IvIndexDelete
{
    public static void main(String[] args) throws Exception
    {
        File fileDir = new File("E:\\data\\lucene");
        File indexDir = new File("E:\\data\\index");
        
        Analyzer luceneAnalyzer = new SmartChineseAnalyzer(Version.LUCENE_42);
        
        IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_42,
                luceneAnalyzer);
        config.setOpenMode(org.apache.lucene.index.IndexWriterConfig.OpenMode.APPEND);
        
        Directory fsDir = new SimpleFSDirectory(indexDir);
        IndexWriter indexWriter = new IndexWriter(fsDir, config);
        File[] txtFiles = fileDir.listFiles();
        long startTime = new Date().getTime();
        
        // 增加document到索引去  
        for (int i = 0; i < txtFiles.length; i++)
        {
            if (txtFiles[i].isFile() && txtFiles[i].getName().endsWith("u.txt"))
            {
                FileInputStream fis = null;
                try
                {
                    fis = new FileInputStream(txtFiles[i]);
                }
                catch (FileNotFoundException fnfe)
                {
                    continue;
                }
                
                try
                {
                    
                    indexWriter.deleteDocuments(new Term("path",
                            txtFiles[i].getPath()));
                }
                finally
                {
                    fis.close();
                }
                
                System.out.println("被删除索引文件:" + txtFiles[i].getCanonicalPath());
            }
        }
        
        indexWriter.forceMerge(10);
        indexWriter.close();
        
        //测试一下索引的时间  
        long endTime = new Date().getTime();
        System.out.println("删除索引耗费时间:" + (endTime - startTime) + " 毫秒!");
    }
}

 

package com.xiva.test.lucene;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.util.Date;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.cn.smart.SmartChineseAnalyzer;
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.index.Term;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.SimpleFSDirectory;
import org.apache.lucene.util.Version;

public class IvIndexUpdate
{
    public static void updateIndex() throws Exception
    {
        File fileDir = new File("E:\\data\\lucene");
        File indexDir = new File("E:\\data\\index");

        Analyzer luceneAnalyzer = new SmartChineseAnalyzer(Version.LUCENE_42);

        IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_42, luceneAnalyzer);

        config.setOpenMode(org.apache.lucene.index.IndexWriterConfig.OpenMode.APPEND);

        Directory fsDir = new SimpleFSDirectory(indexDir);
        IndexWriter indexWriter = new IndexWriter(fsDir, config);
        File[] txtFiles = fileDir.listFiles();
        long startTime = new Date().getTime();

        // 增加document到索引去
        for (int i = 0; i < txtFiles.length; i++)
        {
            if (txtFiles[i].isFile() && txtFiles[i].getName().endsWith("u.txt"))
            {
                FileInputStream fis;
                try
                {
                    fis = new FileInputStream(txtFiles[i]);
                }
                catch (FileNotFoundException fnfe)
                {
                    continue;
                }

                try
                {
                    Document document = new Document();
                    Field fieldPath = new StringField("path", txtFiles[i].getPath(), Field.Store.YES);
                    Field fieldBody = new TextField("body", new BufferedReader(new InputStreamReader(fis, "GBK")));
                    
                    document.add(fieldPath);
                    document.add(fieldBody);

                    indexWriter.updateDocument(new Term("path", txtFiles[i].getPath()), document);
                }
                finally
                {
                    fis.close();
                }

                System.out.println("被更新索引文件:" + txtFiles[i].getCanonicalPath());
            }
        }

        indexWriter.forceMerge(10);
        indexWriter.close();

        // 测试一下索引的时间
        long endTime = new Date().getTime();
        System.out.println("更新索引耗费时间:" + (endTime - startTime) + " 毫秒!");
    }

    public static void main(String[] args) throws Exception
    {
        updateIndex();
    }
}

 

package com.xiva.test.lucene;

import java.io.File;
import java.io.IOException;
import java.util.Date;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.cn.smart.SmartChineseAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
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.FSDirectory;
import org.apache.lucene.util.Version;

public class IvFileSearch
{
    public static void main(String[] args) throws IOException
    {
        String queryString = "索引";
        String field = "body";
        Query query = null;
        TopDocs docs = null;

        File indexDir = new File("F:\\WorkSpace\\EclipseProjects\\luceneIndex");
        IndexReader reader = DirectoryReader.open(FSDirectory.open(indexDir));
        IndexSearcher searcher = new IndexSearcher(reader);

        // StopFilterFactory factory = new StopFilterFactory();
        // factory.getStopWords()
        Analyzer analyzer = new SmartChineseAnalyzer(Version.LUCENE_42);

        try
        {
            long startTime = new Date().getTime();
            QueryParser qp = new QueryParser(Version.LUCENE_42, field, analyzer);
            query = qp.parse(queryString);

            long endTime = new Date().getTime();
            System.out.println("索引耗费时间:" + (endTime - startTime) + " 毫秒!");
        }
        catch (ParseException e)
        {
            e.printStackTrace();
        }

        if (searcher != null)
        {
            docs = searcher.search(query, 25);// 可以分页查询

            ScoreDoc scoreDocs[] = docs.scoreDocs;

            for (int i = 0; i < docs.totalHits; i++)
            {
                Document targetDoc = searcher.doc(scoreDocs[i].doc);
                String path = targetDoc.get("path");
                System.out.println("path:" + path);
            }
        }
    }
}

 

PS:对于数据库操作时,相信大家都有相关的方法去更新或者删除索引,比如及时更新或者使用定时扫描表的方法。数据库本身也具有全文索引的特性,比如Oracle和MSSQL。

 

对与文件的操作,我的解决方法是:可以采用 利用JNA对文件进行监听之观察者模式 这里给出的方法来更新或者删除索引。

分享到:
评论

相关推荐

    lucene全文检索简单索引和搜索实例

    基于lucene 2.4简单的一个索引和搜索实例

    lucene-5.3.0+solr-5.3.0 jar包和文档示例

    Lucene提供了一个简单却强大的应用程式接口,能够做全文索引和搜寻。在Java开发环境里Lucene是一个成熟的免费开源工具。就其本身而言,Lucene是最受欢迎的免费Java资讯检索程式库。人们经常提到资讯检索程式库,虽然...

    lucene入门代码示例

    最受欢迎的java开源全文搜索引擎开发工具包。 提供了完整的查询引擎和... Lucene的目的是为软件开发人员提供一个简单易用的工具包, 以方便在目标系统中实现全文检索功能, 或者是以此为基础建立起完整的全文检索引擎。

    开放源代码的全文检索引擎Lucene

    第一节 全文检索系统与Lucene简介··· 3 一、 什么是全文检索与全文检索系统?··· 3 二、 什么是Lucene?··· 4 三、 Lucene的应用、特点及优势··· 4 四、 本文的重点问题与cLucene项目··· 5 第二...

    基于lucene的搜索引擎总结

    全文索引/检索 为目标列表网站内容建立索引 提供内容的全文检索 自动分类 对目标列表网站内容进行分类 基本流程 网络蜘蛛 功能概要 目标文档地址队列 w/r 目标文档(网页)获取 目标文档保存 文档解析并得到新的目标...

    lucene.net搜索技术,附带学习资料

     做这个示例主要是为了演示一下Lucene.net的功能,它可以对你指定的目录里的.txt,.htm,.html文件进行全文索引,然后对其进行查询。由于如果要索引的目录里文件特别多特别大的话,建立索引需要花费很长的过程,所以...

    【分享:lucene学习资料】---<下载不扣分,回帖加1分,欢迎下载,童叟无欺>

    4. lucene中主要的类 4 4.1. Document文档类 4 4.1.1. 常用方法 4 4.1.2. 示例 4 4.2. Field字段类 4 4.2.1. 构造方法 4 4.2.2. Store类 5 4.2.3. Index类 5 4.2.4. 示例 5 4.3. IndexWriter类 5 4.3.1. 构造方法 5 ...

    csv2lucene:一个简单的实用工具,可为CSV内容编制索引并对其执行全文搜索

    #CSV2Lucene一个简单的实用程序,用于为CSV内容编制索引并对其进行全文搜索。 它依赖于因此您可以获得强大的查询语言##用法该实用程序内置在fatjar中,因此您只需要安装Java 7 java -jar csv2lucene-1.1.2.jar ...

    Luence简单实例

    使用Lucene,可以非常方便给我们的应用增加上全文索引的功能,使用上也非常简单,示例JAVA代码,为了简单好理解,示例是以将内存中加入一些字符串,并通过查询结果,再将结果显示出来

    Elasticsearch 技术解析与实战.zip

    前言 第1章 Elasticsearch入门 1 1.1 Elasticsearch是什么 1 1.1.1 Elasticsearch的历史 2 1.1.2 相关产品 3 1.2 全文搜索 3 1.2.1 Lucene介绍 4 1.2.2 Lucene倒排索引 4 1.3 基础知识 6 1.3.1 Elasticsearch术语及...

    java开源包4

    AutoTips基于搜索引擎Apache Lucene实现。AutoTips提供统一UI。 WAP浏览器 j2wap j2wap 是一个基于Java的WAP浏览器,目前处于BETA测试阶段。它支持WAP 1.2规范,除了WTLS 和WBMP。 Java注册表操作类 jared jared是...

    dwtc-tools:德累斯顿 Web 表语料库 Java 库

    DWTC-Tools:用于处理 Dresden Web Table ... 在语料库上创建 Lucene 索引,包括一些预处理(包webreduce.indexing ) 需要时直接从 Common Crawls S3 访问每个表的原始页面的全文(包webreduce.fulltext ) 应用

    java开源包1

    AutoTips基于搜索引擎Apache Lucene实现。AutoTips提供统一UI。 WAP浏览器 j2wap j2wap 是一个基于Java的WAP浏览器,目前处于BETA测试阶段。它支持WAP 1.2规范,除了WTLS 和WBMP。 Java注册表操作类 jared jared是...

    java开源包11

    AutoTips基于搜索引擎Apache Lucene实现。AutoTips提供统一UI。 WAP浏览器 j2wap j2wap 是一个基于Java的WAP浏览器,目前处于BETA测试阶段。它支持WAP 1.2规范,除了WTLS 和WBMP。 Java注册表操作类 jared jared是...

    java开源包2

    AutoTips基于搜索引擎Apache Lucene实现。AutoTips提供统一UI。 WAP浏览器 j2wap j2wap 是一个基于Java的WAP浏览器,目前处于BETA测试阶段。它支持WAP 1.2规范,除了WTLS 和WBMP。 Java注册表操作类 jared jared是...

    java开源包3

    AutoTips基于搜索引擎Apache Lucene实现。AutoTips提供统一UI。 WAP浏览器 j2wap j2wap 是一个基于Java的WAP浏览器,目前处于BETA测试阶段。它支持WAP 1.2规范,除了WTLS 和WBMP。 Java注册表操作类 jared jared是...

    java开源包6

    AutoTips基于搜索引擎Apache Lucene实现。AutoTips提供统一UI。 WAP浏览器 j2wap j2wap 是一个基于Java的WAP浏览器,目前处于BETA测试阶段。它支持WAP 1.2规范,除了WTLS 和WBMP。 Java注册表操作类 jared jared是...

    java开源包5

    AutoTips基于搜索引擎Apache Lucene实现。AutoTips提供统一UI。 WAP浏览器 j2wap j2wap 是一个基于Java的WAP浏览器,目前处于BETA测试阶段。它支持WAP 1.2规范,除了WTLS 和WBMP。 Java注册表操作类 jared jared是...

    java开源包10

    AutoTips基于搜索引擎Apache Lucene实现。AutoTips提供统一UI。 WAP浏览器 j2wap j2wap 是一个基于Java的WAP浏览器,目前处于BETA测试阶段。它支持WAP 1.2规范,除了WTLS 和WBMP。 Java注册表操作类 jared jared是...

    java开源包8

    AutoTips基于搜索引擎Apache Lucene实现。AutoTips提供统一UI。 WAP浏览器 j2wap j2wap 是一个基于Java的WAP浏览器,目前处于BETA测试阶段。它支持WAP 1.2规范,除了WTLS 和WBMP。 Java注册表操作类 jared jared是...

Global site tag (gtag.js) - Google Analytics