【手把手教你全文检索】Lucene索引的【增、删、改、查】
前言
搞检索的,应该多少都会了解Lucene一些,它开源而且简单上手,官方API足够编写些小DEMO。并且根据倒排索引,实现快速检索。本文就简单的实现增量添加索引,删除索引,通过关键字查询,以及更新索引等操作。
目前博猪使用的不爽的地方就是,读取文件内容进行全文检索时,需要自己编写读取过程(这个solr免费帮我们实现)。而且创建索引的过程比较慢,还有很大的优化空间,这个就要细心下来研究了。
创建索引
Lucene在进行创建索引时,根据前面一篇博客,已经讲完了大体的流程,这里再简单说下:
Directory directory = FSDirectory.open("/tmp/testindex");
IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_CURRENT, analyzer);
IndexWriter iwriter = new IndexWriter(directory, config);
Document doc = new Document();
String text = "This is the text to be indexed.";
doc.add(new Field("fieldname", text, TextField.TYPE_STORED)); iwriter.close();
1 创建Directory,获取索引目录
2 创建词法分析器,创建IndexWriter对象
3 创建document对象,存储数据
4 关闭IndexWriter,提交
/**
* 建立索引
*
* @param args
*/
public static void index() throws Exception { String text1 = "hello,man!";
String text2 = "goodbye,man!";
String text3 = "hello,woman!";
String text4 = "goodbye,woman!"; Date date1 = new Date();
analyzer = new StandardAnalyzer(Version.LUCENE_CURRENT);
directory = FSDirectory.open(new File(INDEX_DIR)); IndexWriterConfig config = new IndexWriterConfig(
Version.LUCENE_CURRENT, analyzer);
indexWriter = new IndexWriter(directory, config); Document doc1 = new Document();
doc1.add(new TextField("filename", "text1", Store.YES));
doc1.add(new TextField("content", text1, Store.YES));
indexWriter.addDocument(doc1); Document doc2 = new Document();
doc2.add(new TextField("filename", "text2", Store.YES));
doc2.add(new TextField("content", text2, Store.YES));
indexWriter.addDocument(doc2); Document doc3 = new Document();
doc3.add(new TextField("filename", "text3", Store.YES));
doc3.add(new TextField("content", text3, Store.YES));
indexWriter.addDocument(doc3); Document doc4 = new Document();
doc4.add(new TextField("filename", "text4", Store.YES));
doc4.add(new TextField("content", text4, Store.YES));
indexWriter.addDocument(doc4); indexWriter.commit();
indexWriter.close(); Date date2 = new Date();
System.out.println("创建索引耗时:" + (date2.getTime() - date1.getTime()) + "ms\n");
}
增量添加索引
Lucene拥有增量添加索引的功能,在不会影响之前的索引情况下,添加索引,它会在何时的时机,自动合并索引文件。
/**
* 增加索引
*
* @throws Exception
*/
public static void insert() throws Exception {
String text5 = "hello,goodbye,man,woman";
Date date1 = new Date();
analyzer = new StandardAnalyzer(Version.LUCENE_CURRENT);
directory = FSDirectory.open(new File(INDEX_DIR)); IndexWriterConfig config = new IndexWriterConfig(
Version.LUCENE_CURRENT, analyzer);
indexWriter = new IndexWriter(directory, config); Document doc1 = new Document();
doc1.add(new TextField("filename", "text5", Store.YES));
doc1.add(new TextField("content", text5, Store.YES));
indexWriter.addDocument(doc1); indexWriter.commit();
indexWriter.close(); Date date2 = new Date();
System.out.println("增加索引耗时:" + (date2.getTime() - date1.getTime()) + "ms\n");
}
删除索引
Lucene也是通过IndexWriter调用它的delete方法,来删除索引。我们可以通过关键字,删除与这个关键字有关的所有内容。如果仅仅是想要删除一个文档,那么最好就顶一个唯一的ID域,通过这个ID域,来进行删除操作。
/**
* 删除索引
*
* @param str 删除的关键字
* @throws Exception
*/
public static void delete(String str) throws Exception {
Date date1 = new Date();
analyzer = new StandardAnalyzer(Version.LUCENE_CURRENT);
directory = FSDirectory.open(new File(INDEX_DIR)); IndexWriterConfig config = new IndexWriterConfig(
Version.LUCENE_CURRENT, analyzer);
indexWriter = new IndexWriter(directory, config); indexWriter.deleteDocuments(new Term("filename",str)); indexWriter.close(); Date date2 = new Date();
System.out.println("删除索引耗时:" + (date2.getTime() - date1.getTime()) + "ms\n");
}
更新索引
Lucene没有真正的更新操作,通过某个fieldname,可以更新这个域对应的索引,但是实质上,它是先删除索引,再重新建立的。
/**
* 更新索引
*
* @throws Exception
*/
public static void update() throws Exception {
String text1 = "update,hello,man!";
Date date1 = new Date();
analyzer = new StandardAnalyzer(Version.LUCENE_CURRENT);
directory = FSDirectory.open(new File(INDEX_DIR)); IndexWriterConfig config = new IndexWriterConfig(
Version.LUCENE_CURRENT, analyzer);
indexWriter = new IndexWriter(directory, config); Document doc1 = new Document();
doc1.add(new TextField("filename", "text1", Store.YES));
doc1.add(new TextField("content", text1, Store.YES)); indexWriter.updateDocument(new Term("filename","text1"), doc1); indexWriter.close(); Date date2 = new Date();
System.out.println("更新索引耗时:" + (date2.getTime() - date1.getTime()) + "ms\n");
}
通过索引查询关键字
Lucene的查询方式有很多种,这里就不做详细介绍了。它会返回一个ScoreDoc的集合,类似ResultSet的集合,我们可以通过域名获取想要获取的内容。
/**
* 关键字查询
*
* @param str
* @throws Exception
*/
public static void search(String str) throws Exception {
directory = FSDirectory.open(new File(INDEX_DIR));
analyzer = new StandardAnalyzer(Version.LUCENE_CURRENT);
DirectoryReader ireader = DirectoryReader.open(directory);
IndexSearcher isearcher = new IndexSearcher(ireader); QueryParser parser = new QueryParser(Version.LUCENE_CURRENT, "content",analyzer);
Query query = parser.parse(str); ScoreDoc[] hits = isearcher.search(query, null, 1000).scoreDocs;
for (int i = 0; i < hits.length; i++) {
Document hitDoc = isearcher.doc(hits[i].doc);
System.out.println(hitDoc.get("filename"));
System.out.println(hitDoc.get("content"));
}
ireader.close();
directory.close();
}
全部代码
package test; import java.io.File;
import java.util.Date;
import java.util.List; import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.LongField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.document.Field.Store;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
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.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version; public class TestLucene {
// 保存路径
private static String INDEX_DIR = "D:\\luceneIndex";
private static Analyzer analyzer = null;
private static Directory directory = null;
private static IndexWriter indexWriter = null; public static void main(String[] args) {
try {
// index();
search("man");
// insert();
// delete("text5");
// update();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 更新索引
*
* @throws Exception
*/
public static void update() throws Exception {
String text1 = "update,hello,man!";
Date date1 = new Date();
analyzer = new StandardAnalyzer(Version.LUCENE_CURRENT);
directory = FSDirectory.open(new File(INDEX_DIR)); IndexWriterConfig config = new IndexWriterConfig(
Version.LUCENE_CURRENT, analyzer);
indexWriter = new IndexWriter(directory, config); Document doc1 = new Document();
doc1.add(new TextField("filename", "text1", Store.YES));
doc1.add(new TextField("content", text1, Store.YES)); indexWriter.updateDocument(new Term("filename","text1"), doc1); indexWriter.close(); Date date2 = new Date();
System.out.println("更新索引耗时:" + (date2.getTime() - date1.getTime()) + "ms\n");
}
/**
* 删除索引
*
* @param str 删除的关键字
* @throws Exception
*/
public static void delete(String str) throws Exception {
Date date1 = new Date();
analyzer = new StandardAnalyzer(Version.LUCENE_CURRENT);
directory = FSDirectory.open(new File(INDEX_DIR)); IndexWriterConfig config = new IndexWriterConfig(
Version.LUCENE_CURRENT, analyzer);
indexWriter = new IndexWriter(directory, config); indexWriter.deleteDocuments(new Term("filename",str)); indexWriter.close(); Date date2 = new Date();
System.out.println("删除索引耗时:" + (date2.getTime() - date1.getTime()) + "ms\n");
}
/**
* 增加索引
*
* @throws Exception
*/
public static void insert() throws Exception {
String text5 = "hello,goodbye,man,woman";
Date date1 = new Date();
analyzer = new StandardAnalyzer(Version.LUCENE_CURRENT);
directory = FSDirectory.open(new File(INDEX_DIR)); IndexWriterConfig config = new IndexWriterConfig(
Version.LUCENE_CURRENT, analyzer);
indexWriter = new IndexWriter(directory, config); Document doc1 = new Document();
doc1.add(new TextField("filename", "text5", Store.YES));
doc1.add(new TextField("content", text5, Store.YES));
indexWriter.addDocument(doc1); indexWriter.commit();
indexWriter.close(); Date date2 = new Date();
System.out.println("增加索引耗时:" + (date2.getTime() - date1.getTime()) + "ms\n");
}
/**
* 建立索引
*
* @param args
*/
public static void index() throws Exception { String text1 = "hello,man!";
String text2 = "goodbye,man!";
String text3 = "hello,woman!";
String text4 = "goodbye,woman!"; Date date1 = new Date();
analyzer = new StandardAnalyzer(Version.LUCENE_CURRENT);
directory = FSDirectory.open(new File(INDEX_DIR)); IndexWriterConfig config = new IndexWriterConfig(
Version.LUCENE_CURRENT, analyzer);
indexWriter = new IndexWriter(directory, config); Document doc1 = new Document();
doc1.add(new TextField("filename", "text1", Store.YES));
doc1.add(new TextField("content", text1, Store.YES));
indexWriter.addDocument(doc1); Document doc2 = new Document();
doc2.add(new TextField("filename", "text2", Store.YES));
doc2.add(new TextField("content", text2, Store.YES));
indexWriter.addDocument(doc2); Document doc3 = new Document();
doc3.add(new TextField("filename", "text3", Store.YES));
doc3.add(new TextField("content", text3, Store.YES));
indexWriter.addDocument(doc3); Document doc4 = new Document();
doc4.add(new TextField("filename", "text4", Store.YES));
doc4.add(new TextField("content", text4, Store.YES));
indexWriter.addDocument(doc4); indexWriter.commit();
indexWriter.close(); Date date2 = new Date();
System.out.println("创建索引耗时:" + (date2.getTime() - date1.getTime()) + "ms\n");
} /**
* 关键字查询
*
* @param str
* @throws Exception
*/
public static void search(String str) throws Exception {
directory = FSDirectory.open(new File(INDEX_DIR));
analyzer = new StandardAnalyzer(Version.LUCENE_CURRENT);
DirectoryReader ireader = DirectoryReader.open(directory);
IndexSearcher isearcher = new IndexSearcher(ireader); QueryParser parser = new QueryParser(Version.LUCENE_CURRENT, "content",analyzer);
Query query = parser.parse(str); ScoreDoc[] hits = isearcher.search(query, null, 1000).scoreDocs;
for (int i = 0; i < hits.length; i++) {
Document hitDoc = isearcher.doc(hits[i].doc);
System.out.println(hitDoc.get("filename"));
System.out.println(hitDoc.get("content"));
}
ireader.close();
directory.close();
}
}
参考资料
http://www.cnblogs.com/xing901022/p/3933675.html
【手把手教你全文检索】Lucene索引的【增、删、改、查】的更多相关文章
- iOS sqlite3 的基本使用(增 删 改 查)
iOS sqlite3 的基本使用(增 删 改 查) 这篇博客不会讲述太多sql语言,目的重在实现sqlite3的一些基本操作. 例:增 删 改 查 如果想了解更多的sql语言可以利用强大的互联网. ...
- 好用的SQL TVP~~独家赠送[增-删-改-查]的例子
以前总是追求新东西,发现基础才是最重要的,今年主要的目标是精通SQL查询和SQL性能优化. 本系列主要是针对T-SQL的总结. [T-SQL基础]01.单表查询-几道sql查询题 [T-SQL基础] ...
- iOS FMDB的使用(增,删,改,查,sqlite存取图片)
iOS FMDB的使用(增,删,改,查,sqlite存取图片) 在上一篇博客我对sqlite的基本使用进行了详细介绍... 但是在实际开发中原生使用的频率是很少的... 这篇博客我将会较全面的介绍FM ...
- django ajax增 删 改 查
具于django ajax实现增 删 改 查功能 代码示例: 代码: urls.py from django.conf.urls import url from django.contrib impo ...
- ADO.NET 增 删 改 查
ADO.NET:(数据访问技术)就是将C#和MSSQL连接起来的一个纽带 可以通过ADO.NET将内存中的临时数据写入到数据库中 也可以将数据库中的数据提取到内存中供程序调用 ADO.NET所有数据访 ...
- MVC EF 增 删 改 查
using System;using System.Collections.Generic;using System.Linq;using System.Web;//using System.Data ...
- python基础中的四大天王-增-删-改-查
列表-list-[] 输入内存储存容器 发生改变通常直接变化,让我们看看下面列子 增---默认在最后添加 #append()--括号中可以是数字,可以是字符串,可以是元祖,可以是集合,可以是字典 #l ...
- js数组的管理[增,删,改,查]
今天在设计表单的时候遇到对数组的一些处理的问题,比如说怎么创建一个数组,然后牵扯到数组的增删改查的方法.请看API FF: Firefox, N: Netscape, IE: Internet Exp ...
- day 37-8 关于mysql 的增 删 改 查 及联合列表
1 VARCHAR : 字符串的意思 (括号内的数字代表尾数) 输入的字符串在这个范围内都行 CHAR :字符串的意思(区别就有几位数字 必须写几位) INT 整数(位数) 输入的数字 ...
- list 增 删 改 查 及 公共方法
# 热身题目:增加名字,并且按q(不论大小写)退出程序 li = ['taibai','alex','wusir','egon','女神'] while 1: username = input('&g ...
随机推荐
- 【转】Eclipse打JAR包,插件FatJar安装与使用
原文地址:http://blog.csdn.net/jikeyzhang/article/details/4731968 下载RUL: 下载fatJar插件,解压缩后是一个.../plugins/(n ...
- 一名小小的SQL Server DBA想谈一下SQL Server的能力
一名小小的SQL Server DBA想谈一下SQL Server的能力 百度上暂时还没有搜索到相关的个人写的比较有价值的文章,至少在中文网络的世界里面没有 但是在微软的网站有这样一篇文章:<比 ...
- CentOs 7怎么联网
在安装好Centos7后,网络还不能正常使用,需要我们手动配置.并且Linux的网络配置并不太容易,新手经常不知道从何开始.为了解决这个令大家头疼的问题,我在此将成功的配置过程与大家分享.希望大家都能 ...
- GitHub详解(GitHub for Windows)
GitHub详解 GitHub 是一个共享虚拟主机服务,用于存放使用Git版本控制的软件代码和内容项目.它由GitHub公司(曾称Logical Awesome)的开发者Chris Wanstrath ...
- 源代码版本管理与项目管理软件的认识与github的注册
源代码版本管理软件: 主要有:svn,cvs,hg,git,VSS 这些工具主要是一种记录代码更改历史, 可以无限回溯, 用于代码管理,多个程序员开发协作的工具.Perforce,StarTeam)- ...
- VS2012下配置MPI
并行处理结课实验,要用到MPI编程,我的电脑和VS2012都是64位的,以为MPICH也得是64位才行,结果饶了很大的弯——配置正确,添加引用之后,仍然无法识别MPI函数. 后来换了个32位的MPIC ...
- Nginx + CGI/FastCGI + C/Cpp
接着上篇<Nginx安装与使用>,本篇介绍CGI/FASTCGI的原理.及如何使用C/C++编写简单的CGI/FastCGI,最后将CGI/FASTCGI部署到nginx.内容大纲如下: ...
- Java集合List模拟“洗牌”操作
Collection工具类为操作List集合提供了几个有用的方法: reverse().shuffle().sort().swap().rotate(). 小例子: 使用shuffle(),方法模拟洗 ...
- Ajax跨域访问XML数据的另一种方式——使用YQL查询语句
XML数据默认是不能在客户端通过Ajax跨域请求读取的,一般的做法是在服务器上写一个简单的代理程序,将远程XML的数据先读到本地服务器,然后客户端再从本地服务器通过Ajax来请求.由于我们不能对数据源 ...
- Redis主从复制问题和扩容问题的解决思路
转载于:http://www.itxuexiwang.com/a/shujukujishu/redis/2016/0216/106.html?1455867541 一.解决主从复制问题 当使用Redi ...