你好,游客 登录 注册 搜索
背景:
阅读新闻

Lucene 入门教程

[日期:2015-08-01] 来源:Linux社区  作者:always-online [字体: ]

一、Lucene简介

Lucene是apache下的一个靠性能的、功能全面的用纯java开发的一个全文搜索引擎库。它几乎适合任何需要全文搜索应用程序,尤其是跨平台。Lucene是开源的免费的工程。Lucene使用简单但是提供的功能非常强大。相关特点如下:

  • 在硬件上的速度超过150GB/小时
  • 更小的内存需求,只需要1MB堆空间
  • 快速地增加索引、与批量索引
  • 索引的大小大于为被索引文本的20%-30%

Lucene下载地址为:http://lucene.apache.org/

文本示例工程使用maven构建,Lucene版本为5.2.1。相关依赖文件如下:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.shh</groupId>
    <artifactId>lucene</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>lucene Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <lucene.version>5.2.1</lucene.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.apache.lucene</groupId>
            <artifactId>lucene-core</artifactId>
            <version>${lucene.version}</version>
        </dependency>

        <dependency>
            <groupId>org.apache.lucene</groupId>
            <artifactId>lucene-queryparser</artifactId>
            <version>${lucene.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.lucene</groupId>
            <artifactId>lucene-analyzers-common</artifactId>
            <version>${lucene.version}</version>
        </dependency>

        <!-- 分词器 -->
        <dependency>
            <groupId>org.apache.lucene</groupId>
            <artifactId>lucene-analyzers-smartcn</artifactId>
            <version>${lucene.version}</version>
        </dependency>

        <dependency>
            <groupId>org.apache.lucene</groupId>
            <artifactId>lucene-highlighter</artifactId>
            <version>${lucene.version}</version>
        </dependency>
    </dependencies>

    <build>
        <finalName>lucene</finalName>
    </build>
</project>

二、示例

1、索引的创建

相关代码如下:

package com.test.lucene;

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.Store;
import org.apache.lucene.document.IntField;
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.IndexWriterConfig.OpenMode;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

/**
 * 创建索引
 */
public class IndexCreate {
   
    public static void main(String[] args) {
        // 指定分词技术,这里使用的是标准分词
        Analyzer analyzer = new StandardAnalyzer();

        // indexWriter的配置信息
        IndexWriterConfig indexWriterConfig = new IndexWriterConfig(analyzer);

        // 索引的打开方式:没有则创建,有则打开
        indexWriterConfig.setOpenMode(OpenMode.CREATE_OR_APPEND);

        Directory directory = null;
        IndexWriter indexWriter = null;
        try {
            // 索引在硬盘上的存储路径
            directory = FSDirectory.open(Paths.get("D://index/test"));
            //indexWriter用来创建索引文件
            indexWriter = new IndexWriter(directory, indexWriterConfig);
        } catch (IOException e) {
            e.printStackTrace();
        }
       
        //创建文档一
        Document doc1 = new Document();
        doc1.add(new StringField("id", "abcde", Store.YES));
        doc1.add(new TextField("content", "中国广州", Store.YES));
        doc1.add(new IntField("num", 1, Store.YES));

        //创建文档二
        Document doc2 = new Document();
        doc2.add(new StringField("id", "asdff", Store.YES));
        doc2.add(new TextField("content", "中国上海", Store.YES));
        doc2.add(new IntField("num", 2, Store.YES));

        try {
            //添加需要索引的文档
            indexWriter.addDocument(doc1);
            indexWriter.addDocument(doc2);
 
            // 将indexWrite操作提交,如果不提交,之前的操作将不会保存到硬盘
            // 但是这一步很消耗系统资源,索引执行该操作需要有一定的策略
            indexWriter.commit();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            try {
                indexWriter.close();
                directory.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

2、搜索

相关代码如下:

package com.test.lucene;

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.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.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

/**
 * 搜索
 */
public class IndexSearch {
   
    public static void main(String[] args) {
        //索引存放的位置
        Directory directory = null;
        try {
            // 索引硬盘存储路径
            directory = FSDirectory.open(Paths.get("D://index/test"));
            // 读取索引
            DirectoryReader directoryReader = DirectoryReader.open(directory);
            // 创建索引检索对象
            IndexSearcher searcher = new IndexSearcher(directoryReader);
            // 分词技术
            Analyzer analyzer = new StandardAnalyzer();
            // 创建Query
            QueryParser parser = new QueryParser("content", analyzer);
            Query query = parser.parse("广州");// 查询content为广州的
            // 检索索引,获取符合条件的前10条记录
            TopDocs topDocs = searcher.search(query, 10);
            if (topDocs != null) {
                System.out.println("符合条件的记录为: " + topDocs.totalHits);
                for (int i = 0; i < topDocs.scoreDocs.length; i++) {
                    Document doc = searcher.doc(topDocs.scoreDocs[i].doc);
                    System.out.println("id = " + doc.get("id"));
                    System.out.println("content = " + doc.get("content"));
                    System.out.println("num = " + doc.get("num"));
                }
            }
            directory.close();
            directoryReader.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}

运行结果如下:

三、Lucene的工作原理

Lucene全文搜索分为两个步骤:

索引创建:将数据(包括数据库数据、文件等)进行信息提取,并创建索引文件。

搜索索引:根据用户的搜索请求,对创建的索引进行搜索,并将搜索的结果返回给用户。

相关示意图如下:

还不过瘾,看看分割线下关于Lucene的更多相关内容

--------------------------------------分割线 --------------------------------------

基于Lucene多索引进行索引和搜索 http://www.linuxidc.com/Linux/2012-05/59757.htm

Lucene 实战(第2版) 中文版 配套源代码 http://www.linuxidc.com/Linux/2013-10/91055.htm

Lucene 实战(第2版) PDF高清中文版 http://www.linuxidc.com/Linux/2013-10/91052.htm

使用Lucene-Spatial实现集成地理位置的全文检索 http://www.linuxidc.com/Linux/2012-02/53117.htm

Lucene + Hadoop 分布式搜索运行框架 Nut 1.0a9 http://www.linuxidc.com/Linux/2012-02/53113.htm

Lucene + Hadoop 分布式搜索运行框架 Nut 1.0a8 http://www.linuxidc.com/Linux/2012-02/53111.htm

Lucene + Hadoop 分布式搜索运行框架 Nut 1.0a7 http://www.linuxidc.com/Linux/2012-02/53110.htm

Project 2-1: 配置Lucene, 建立WEB查询系统[Ubuntu 10.10] http://www.linuxidc.com/Linux/2010-11/30103.htm

--------------------------------------分割线 --------------------------------------

Lucene 的详细介绍请点这里
Lucene 的下载地址请点这里 

本文永久更新链接地址http://www.linuxidc.com/Linux/2015-08/120892.htm

linux
相关资讯       Lucene教程  Lucene入门教程  Lucene入门 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款