在Lucene对文本进行处理的过程中,可以大致分为三大部分:

1、索引文件:提取文档内容并分析,生成索引

2、搜索内容:搜索索引内容,根据搜索关键字得出搜索结果

3、分析内容:对搜索词汇进行分析,生成Quey对象。

注:事实上,除了最基本的完全匹配搜索以外,其它都需要在搜索前进行分析。

如不加分析步骤,则搜索JAVA,是没有结果的,因为在索引过程中已经将词汇均转化为小写,而此处搜索时则要求关键字完全匹配。

使用了QueryParser类以后,则根据Analyzer的具体实现类,对搜索词汇进行分析,如大小写转换,java and ant等的搜索词解释等。

一、索引文件

基本步骤如下:

1、创建索引库IndexWriter

2、根据文件创建文档Document

3、向索引库中写入文档内容

package com.ljh.search.index;

import java.io.File;
import java.io.FileReader;
import java.io.IOException; import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.LongField;
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;
import org.apache.lucene.util.Version; // 1、创建索引库IndexWriter
// 2、根据文件创建文档Document
// 3、向索引库中写入文档内容 public class IndexFiles { public static void main(String[] args) throws IOException { String usage = "java IndexFiles"
+ " [-index INDEX_PATH] [-docs DOCS_PATH] \n\n"
+ "This indexes the documents in DOCS_PATH, creating a Lucene index"
+ "in INDEX_PATH that can be searched with SearchFiles"; String indexPath = null;
String docsPath = null;
for (int i = 0; i < args.length; i++) {
if ("-index".equals(args[i])) {
indexPath = args[i + 1];
i++;
} else if ("-docs".equals(args[i])) {
docsPath = args[i + 1];
i++;
}
} if (docsPath == null) {
System.err.println("Usage: " + usage);
System.exit(1);
} final File docDir = new File(docsPath);
if (!docDir.exists() || !docDir.canRead()) {
System.out
.println("Document directory '"
+ docDir.getAbsolutePath()
+ "' does not exist or is not readable, please check the path");
System.exit(1);
} IndexWriter writer = null;
try {
// 1、创建索引库IndexWriter
writer = getIndexWriter(indexPath);
index(writer, docDir);
} catch (IOException e) {
e.printStackTrace();
} finally {
writer.close();
} } private static IndexWriter getIndexWriter(String indexPath)
throws IOException { Directory indexDir = FSDirectory.open(new File(indexPath)); IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_48,
new StandardAnalyzer(Version.LUCENE_48)); IndexWriter writer = new IndexWriter(indexDir, iwc); return writer;
} private static void index(IndexWriter writer, File file) throws IOException { if (file.isDirectory()) {
String[] files = file.list();
if (files != null) {
for (int i = 0; i < files.length; i++) {
index(writer, new File(file, files[i]));
}
}
} else {
// 2、根据文件创建文档Document
Document doc = new Document();
Field pathField = new StringField("path", file.getPath(),
Field.Store.YES);
doc.add(pathField);
doc.add(new LongField("modified", file.lastModified(),
Field.Store.NO));
doc.add(new TextField("contents", new FileReader(file)));
System.out.println("Indexing " + file.getName()); // 3、向索引库中写入文档内容
writer.addDocument(doc);
} } }

(1)使用“java indexfiles -index d:/index -docs d:/tmp”运行程序,索引d:/tmp中的文件,并将索引文件放置到d:/index。

(2)上述生成的索引文件可以使用Luke进行查看。目前Luke已迁移至github进行托管。

二、搜索文件

1、打开索引库IndexSearcher

2、根据关键词进行搜索

3、遍历结果并处理

package com.ljh.search.search;

//1、打开索引库IndexSearcher
//2、根据关键词进行搜索
//3、遍历结果并处理
import java.io.File;
import java.io.IOException; import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory; public class Searcher {
public static void main(String[] args) throws IOException { String indexPath = null;
String term = null;
for (int i = 0; i < args.length; i++) {
if ("-index".equals(args[i])) {
indexPath = args[i + 1];
i++;
} else if ("-term".equals(args[i])) {
term = args[i + 1];
i++;
}
} System.out.println("Searching " + term + " in " + indexPath); // 1、打开索引库
Directory indexDir = FSDirectory.open(new File(indexPath));
IndexReader ir = DirectoryReader.open(indexDir);
IndexSearcher searcher = new IndexSearcher(ir); // 2、根据关键词进行搜索
TopDocs docs = searcher.search(
new TermQuery(new Term("contents", term)), 20); // 3、遍历结果并处理
ScoreDoc[] hits = docs.scoreDocs;
System.out.println(hits.length);
for (ScoreDoc hit : hits) {
System.out.println("doc: " + hit.doc + " score: " + hit.score);
} ir.close(); } }

三、分析

事实上,除了最基本的完全匹配搜索以外,其它都需要在搜索前进行分析。

如不加分析步骤,则搜索JAVA,是没有结果的,因为在索引过程中已经将词汇均转化为小写,而此处搜索时则要求关键字完全匹配。

使用了QueryParser类以后,则根据Analyzer的具体实现类,对搜索词汇进行分析,如大小写转换,java and ant等的搜索词解释等。

分析过程有2个基本步骤:

1、生成QueryParser对象

2、调用QueryParser.parse()生成Query()对象。

具体代码,将下述代码:

		// 2、根据关键词进行搜索
TopDocs docs = searcher.search(
new TermQuery(new Term("contents", term)), 20);

用以下代替:

		// 2、根据关键词进行搜索
/*TopDocs docs = searcher.search(
new TermQuery(new Term("contents", term)), 10);*/
QueryParser parser = new QueryParser(Version.LUCENE_48, "contents", new SimpleAnalyzer(Version.LUCENE_48));
Query query = null;
try {
query = parser.parse(term);
} catch (ParseException e) {
e.printStackTrace();
}
TopDocs docs = searcher.search(query, 30);

【Lucene4.8教程之一】使用Lucene4.8进行索引及搜索的基本操作的更多相关文章

  1. 【Lucene4.8教程之中的一个】使用Lucene4.8进行索引及搜索的基本操作

    版权声明:本文为博主原创文章.转载请注明来自http://blog.csdn.net/jediael_lu/ https://blog.csdn.net/jediael_lu/article/deta ...

  2. 【Lucene4.8教程之三】搜索

    1.关键类 Lucene的搜索过程中涉及的主要类有以下几个: (1)IndexSearcher:执行search()方法的类 (2)IndexReader:对索引文件进行读操作,并为IndexSear ...

  3. 【Lucene4.8教程之二】索引

    一.基础内容 0.官方文档说明 (1)org.apache.lucene.index provides two primary classes: IndexWriter, which creates ...

  4. 【Lucene4.8教程之三】搜索 2014-06-21 09:53 1532人阅读 评论(0) 收藏

    1.关键类 Lucene的搜索过程中涉及的主要类有以下几个: (1)IndexSearcher:执行search()方法的类 (2)IndexReader:对索引文件进行读操作,并为IndexSear ...

  5. 【Lucene4.8教程之二】索引 2014-06-16 11:30 3845人阅读 评论(0) 收藏

    一.基础内容 0.官方文档说明 (1)org.apache.lucene.index provides two primary classes: IndexWriter, which creates ...

  6. MWeb for Mac使用教程-如何在文档库中快速搜索

    使用MWeb for Mac专业的 Markdown 编辑写作软件,可以让你随时记录自己的想法,灵感,创意,为您的工作节省宝贵的时间.本篇文章带来的是MWeb for Mac如何在文档库中快速搜索使用 ...

  7. 【Lucene4.8教程之四】分析

    1.基础内容 (1)相关概念 分析(Analysis),在Lucene中指的是将域(Field)文本转换成最主要的索引表示单元--项(Term)的过程.在搜索过程中,这些项用于决定什么样的文档可以匹配 ...

  8. 【Lucene4.8教程之五】Luke

    一.Luke基本内容 1.Luke简介 Luke可用于查看Lucene创建的索引,并对其进行基本操作. 2.创建Luke (1)从Github上下载源文件 https://github.com/tar ...

  9. 【Lucene4.8教程之六】QueryParser与Query子类:如何生成Query对象

    一.概述 1.对于一个搜索而言,其核心语句为: searcher.search(query, 10); 此时,其最重要的参数为一个Qeury对象.构造一个Query对象有2种方法: (1)使用Quer ...

随机推荐

  1. C++服务器设计(六):设备连接的生命周期管理

    生命周期介绍 每一个服务器系统的新连接从建立开始时,均会经历多个阶段.比如连接的建立,登录的验证,退出前的资源释放等.同时在具体的消息处理中,还会遇到不可识别的消息事件,或者消息处理时出现数据错误等. ...

  2. 【solr专题之四】关于VelocityResponseWriter

    一.关于Velocity的基本配置 在Solr中,可以以多种方式返回搜索结果,如单纯的文本回复(XML.JSON.CSV等),也可以返回velocity,js等格式.而VelocityResponse ...

  3. 【solr专题之四】在Tomcat 中部署Solr4.x

    1.安装Tomcat (1)下载并解压至/opt/tomcat中 # cd /opt/jediael # tar -zxvf apache-tomcat-7.0.54.tar.gz # mv apac ...

  4. js控制浏览器后退

    <script type="text/javascript"> window.history.forward(1); </script>

  5. debian gnome 3插件

    1.gnome 配置-安装插件 http://maxubuntu.blogspot.com/2012/09/debian-gnome3.html hunagqf|hunaqf2|hunaqf3 2.快 ...

  6. 微软的OneDrive研究~

    Dropbox 很好,唯一觉得不爽的是只能同步指定的目录.不过被墙之后就不那么方便了,所以改用微软的 Live Mesh,缺点是支持的设备少(仅 PC 和 Mac). https://technet. ...

  7. 在一个exe文件中查找指定内容,找到则返回起始位置, 否则返回0

    //在一个exe文件中查找指定内容,找到则返回起始位置, 否则返回0//如果某字符串, 直接传入字符串进来//如果要查找16进制,则用如下格式传参进来: #$1A#$2A#$3A function F ...

  8. Implement Hash Map Using Primitive Types

    A small coding test that I encountered today. Question Using only primitive types, implement a fixed ...

  9. hdu 2079 选课时间_母函数

    题意:需要学够n学分,有k个情况(x学分,y个相同学分的课) 解法:套母函数模板 #include <iostream> #include<cstdio> using name ...

  10. iOS Get方式带中文不能请求网络

    今天发现一个蛋疼的问题,使用ASIHTTPRequest Get方式请求数据时候带中文,iOS客户端不能正确进行网络请求. NSURL *url = [NSURL URLWithString:@htt ...