Lucene索引的【增、删、改、查】
前言
搞检索的,应该多少都会了解Lucene一些,它开源而且简单上手,官方API足够编写些小DEMO。并且根据倒排索引,实现快速检索。本文就简单的实现增量添加索引,删除索引,通过关键字查询,以及更新索引等操作。
目前博猪使用的不爽的地方就是,读取文件内容进行全文检索时,需要自己编写读取过程(这个solr免费帮我们实现)。而且创建索引的过程比较慢,还有很大的优化空间,这个就要细心下来研究了。
创建索引
Lucene在进行创建索引时,根据前面一篇博客,已经讲完了大体的流程,这里再简单说下:
1 Directory directory = FSDirectory.open("/tmp/testindex");
2 IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_CURRENT, analyzer);
3 IndexWriter iwriter = new IndexWriter(directory, config);
4 Document doc = new Document();
5 String text = "This is the text to be indexed.";
6 doc.add(new Field("fieldname", text, TextField.TYPE_STORED)); iwriter.close();
1 创建Directory,获取索引目录
2 创建词法分析器,创建IndexWriter对象
3 创建document对象,存储数据
4 关闭IndexWriter,提交
1 创建Directory,获取索引目录 2 创建词法分析器,创建IndexWriter对象 3 创建document对象,存储数据 4 关闭IndexWriter,提交
增量添加索引
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();
}
}
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 ...
- list 增 删 改 查 及 公共方法
# 热身题目:增加名字,并且按q(不论大小写)退出程序 li = ['taibai','alex','wusir','egon','女神'] while 1: username = input('&g ...
- 简单的php数据库操作类代码(增,删,改,查)
这几天准备重新学习,梳理一下知识体系,同时按照功能模块划分做一些东西.所以.mysql的操作成为第一个要点.我写了一个简单的mysql操作类,实现数据的简单的增删改查功能. 数据库操纵基本流程为: 1 ...
- MongoDB增 删 改 查
增 增加单篇文档 > db.stu.insert({sn:'001', name:'lisi'}) WriteResult({ "nInserted" : 1 }) > ...
随机推荐
- (转)SQL SERVER 日志已满的处理方法
本文转载自:http://www.cnblogs.com/eycbest/archive/2012/01/04/2311567.html 事务日志文件Transaction Log File是用来记录 ...
- 使用Amoeba实现mysql读写分离机制
Amoeba的实用指南 http://docs.hexnova.com/amoeba/ 如何实现mysql读写分离 : 通常来说有两种方式: 1,应用程序层实现 2,中间件层实现 应用层实现 应用层实 ...
- httpclient的几种请求URL的方式
一.httpclient项目有两种使用方式.一种是commons项目,这一个就只更新到3.1版本了.现在挪到了HttpComponents子项目下了,这里重点讲解HttpComponents下面的ht ...
- json中key大小写转换
最近工作中遇到json格式的字符串中的key为大写的,需要转换成小写的来解析,开始想使用正则来替换,结果不是很方便,后来考虑把JSONObject重新来封装. 如下json格式:{PWACHECKIN ...
- CentOS6.5 安装mysql-5.7.9
转自:http://forrest-lv.iteye.com/blog/2260703 安装前,需要检查是否已经有mysql服务进程,是否已经装过mysql; 这点很重要,我之前安装CentOS的同 ...
- HttpContext.Current并非无处不在
阅读目录 开始 无处不在的HttpContext HttpContext.Current到底保存在哪里? HttpContext并非无处不在! 如何获取文件绝对路径? 异步调用中如何访问HttpCon ...
- jQuery的文档操作
1.插入操作 一.父元素.append(子元素) 追加某元素 父元素中添加新的元素 var oli = document.createElement('li'); oli.innerHTML = '哈 ...
- 基于C++11实现的线程池
1.C++11中引入了lambada表达式,很好的支持异步编程 2.C++11中引入了std::thread,可以很方便的构建线程,更方便的可移植特性 3.C++11中引入了std::mutex,可以 ...
- 可视化库-Matplotlib-直方图(第四天)
1.plt.hist(array, bins, color) # array表示数值, bins表示的是bin的范围 data = np.random.normal(0, 20, 1000) # 画 ...
- 提示框一段时间以后消失setTimeout
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...