用Lucene4.5对中文文本建立索引
这里需要完成一个能对txt文本建立索引,并能完成检索查询。完成这个功能,使用的是Lucene4.5,同时使用其自带的中文分析器。
准备工作是在一个文件夹里面建一些txt文件,这是我的文件结构:
首先要对这些文本建立索引,代码如下
package com.test; import java.io.*;
import java.util.ArrayList;
import java.util.List;
import org.apache.lucene.analysis.cn.smart.SmartChineseAnalyzer;
import org.apache.lucene.document.*; 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; public class Indexer { /**
* @param args
*/ private static String fileInput = "C:\\Users\\Press-Lab\\Desktop\\五月天歌词文件";
//此处是索引存放的路径
private static String indexPath = "C:\\Users\\Press-Lab\\Desktop\\index"; public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
//此处去处txt的内容和路径,装入list中,方便下一步放入document中
File[] files = new File(fileInput).listFiles();
List<FileBag> list = new ArrayList<FileBag>();
for(File f : files){
BufferedReader br = new BufferedReader(new FileReader(f));
StringBuffer sb = new StringBuffer();
String line = null;
while((line = br.readLine()) != null){
sb.append(line);
}
br.close();
FileBag fileBag = new FileBag();
fileBag.setContent(sb.toString());
fileBag.setPath(f.getAbsolutePath());
list.add(fileBag);
} //此处为建立索引
Directory dir = FSDirectory.open(new File(indexPath));
//此处使用自带的中文分析器
SmartChineseAnalyzer analyzer = new SmartChineseAnalyzer(Version.LUCENE_45);
IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_45, analyzer);
IndexWriter writer = new IndexWriter(dir, config); //对list中的每一个对象,分别连击索引
for(FileBag fileBag : list){
Document doc = new Document();
doc.add(new Field("contents", fileBag.getContent(), Field.Store.YES,Field.Index.ANALYZED));
doc.add(new StringField("path", fileBag.getPath(), Field.Store.YES));
writer.addDocument(doc);
} writer.close(); } }
//建立一个与txt对应的domain对象
class FileBag{
private String content;
private String path;
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
} }
在这段代码中,我对文本进行了存储,一般情况下是无需存储的,这里为为了方便查看结果才进行存储。
特别注意代码的54行,如果使用Lucene4.5推荐的TextField,这无法建立索引。不知道这是个什么原因,有人解决过这个问题的麻烦告知下。
下面是进行检索的代码:
package com.test; import java.io.*; import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.cn.smart.SmartChineseAnalyzer;
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.index.Term; 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.TermQuery;
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 com.dong.Constants; public class Seacher { /**
* @param args
*/
private static String indexPath = "C:\\Users\\Press-Lab\\Desktop\\index";
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub Directory dir=FSDirectory.open(new File(indexPath));
IndexReader reader=DirectoryReader.open(dir);
IndexSearcher searcher=new IndexSearcher(reader);
//此处也需要是用中文分析器
SmartChineseAnalyzer analyzer = new SmartChineseAnalyzer(Version.LUCENE_45);
QueryParser parser = new QueryParser(Version.LUCENE_45, "contents", analyzer);
Query query = parser.parse("如果") ; TopDocs topdocs=searcher.search(query, 5);
ScoreDoc[] scoreDocs=topdocs.scoreDocs; System.out.println("共有数据:" + topdocs.scoreDocs.length + "条");
for(int i=0; i < scoreDocs.length; i++) {
int doc = scoreDocs[i].doc;
Document document = searcher.doc(doc);
System.out.println("第" + i + "条文本的路径是: " + document.get("path"));
System.out.println("第" + i + "条文本内容是: " + document.get("contents")); }
reader.close();
} }
这里需要注意的是,查询时候也需要中文分析器。
下一篇要做的是,实现索引的分页查询。
用Lucene4.5对中文文本建立索引的更多相关文章
- Lucene4.9学习笔记——Lucene建立索引
基本上创建索引需要三个步骤: 1.创建索引库IndexWriter对象 2.根据文件创建文档Document 3.向索引库中写入文档内容 这其中主要涉及到了IndexWriter(索引的核心组件,用于 ...
- 万字总结Keras深度学习中文文本分类
摘要:文章将详细讲解Keras实现经典的深度学习文本分类算法,包括LSTM.BiLSTM.BiLSTM+Attention和CNN.TextCNN. 本文分享自华为云社区<Keras深度学习中文 ...
- lucene 建立索引的过程
时间 -- :: CSDN博客 原文 http://blog.csdn.net/caohaicheng/article/details/ 看lucene主页(http://lucene.apach ...
- 【Lucene4.8教程之二】索引
一.基础内容 0.官方文档说明 (1)org.apache.lucene.index provides two primary classes: IndexWriter, which creates ...
- (转)Mysql哪些字段适合建立索引
工作中处理数据时,发现某个表的数据达近亿条,所以要为表建索引提高查询性能,以下两篇文章总结的很好,记录一下,以备后用. 数据库建立索引常用的规则如下: 1.表的主键.外键必须有索引: 2.数据量超过3 ...
- Mysql哪些字段适合建立索引
数据库建立索引常用的规则如下: 1.表的主键.外键必须有索引: 2.数据量超过300的表应该有索引: 3.经常与其他表进行连接的表,在连接字段上应该建立索引: 4.经常出现在Where子句中的字段,特 ...
- mysql中建立索引的一些原则
1.先存数据,再建索引 有索引的好处是搜索比较快但是在有索引的前提下进行插入.更新操作会很慢 2.不要对规模小的数据表建立索引,数据量超过300的表应该有索引:对于规模小的数据表建立索引 不仅不会提高 ...
- MongoDB优化,建立索引实例及索引机制原理讲解
MongoDB优化,建立索引实例及索引机制原理讲解 为什么需要索引? 当你抱怨MongoDB集合查询效率低的时候,可能你就需要考虑使用索引了,为了方便后续介绍,先科普下MongoDB里的索引机制(同样 ...
- mysql建立索引的一些小规则
1.表的主键.外键必须有索引: 2.数据量超过300的表应该有索引: 3.经常与其他表进行连接的表,在连接字段上应该建立索引: 4.经常出现在Where子句中的字段,特别是大表的字段,应该建立索引: ...
随机推荐
- shell脚本遍历子目录
#!/bin/bashsource /etc/profile tool_path=/data/rsync_clientroot_path=/data/log ####yyyy-mm-dd¸ñʽdat ...
- 【Selenium-WebDriver自学】Selenium TestNG(十四)
==================================================================================================== ...
- [UnityShader基础]01.渲染队列
unity中定义了5个渲染队列: 1.Background,对应索引号1000,该队列最先被渲染 2.Geometry,对应索引号2000,默认的渲染队列,大多数物体都使用该队列,不透明物体使用该队列 ...
- python库pandas
由于在机器学习中经常以矩阵的方式来表现数据,那么我们就需要一种数据结构来存储和处理矩阵.pandas库就是这样一个工具. 本文档是一个学习笔记,记录一些常用的命令,原文:http://www.cnbl ...
- ROS进阶学习手记 7 -- RViz仿真实例1
[任务2]: 用simulator: RViz 工具,完成对小车的建模,名字drive RViz = dvrv, 用 dvrv_node 发布topic和数据格式,向它发送位置指令,使它能接受 ...
- Check Kernel version of J2EE Engine
1912674 - How to check kernel version of an AS Java Two types of the kernel are in SAP NetWeaver Jav ...
- 1.python进程、线程、多线程
2018-07-16 1.进程 简单理解:进程就是一段程序执行的过程. 广义理解:进程就是一个具有一定独立功能的程序关于某个数据集合的一次运行活动. 进程是cpu调度和分配的基本的分配单元,也是基本的 ...
- 白鹭引擎 - 对象的添加与删除 ( 开关效果 addChild, removeChild )
class Main extends egret.DisplayObjectContainer { /** * Main 类构造器, 初始化的时候自动执行, ( 子类的构造函数必须调用父类的构造函数 ...
- python linux 下开发环境搭建
1.1: 在虚拟环境目录下安装 ipython => pip install ipython 1.2: 简单的使用 => ipthyon => print("heollo ...
- keepalived nginx 双机热备图文讲解
http://blog.csdn.net/wanglei_storage/article/details/51175418