前言

  搞检索的,应该多少都会了解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索引的【增、删、改、查】的更多相关文章

  1. iOS sqlite3 的基本使用(增 删 改 查)

    iOS sqlite3 的基本使用(增 删 改 查) 这篇博客不会讲述太多sql语言,目的重在实现sqlite3的一些基本操作. 例:增 删 改 查 如果想了解更多的sql语言可以利用强大的互联网. ...

  2. 好用的SQL TVP~~独家赠送[增-删-改-查]的例子

    以前总是追求新东西,发现基础才是最重要的,今年主要的目标是精通SQL查询和SQL性能优化.  本系列主要是针对T-SQL的总结. [T-SQL基础]01.单表查询-几道sql查询题 [T-SQL基础] ...

  3. iOS FMDB的使用(增,删,改,查,sqlite存取图片)

    iOS FMDB的使用(增,删,改,查,sqlite存取图片) 在上一篇博客我对sqlite的基本使用进行了详细介绍... 但是在实际开发中原生使用的频率是很少的... 这篇博客我将会较全面的介绍FM ...

  4. django ajax增 删 改 查

    具于django ajax实现增 删 改 查功能 代码示例: 代码: urls.py from django.conf.urls import url from django.contrib impo ...

  5. ADO.NET 增 删 改 查

    ADO.NET:(数据访问技术)就是将C#和MSSQL连接起来的一个纽带 可以通过ADO.NET将内存中的临时数据写入到数据库中 也可以将数据库中的数据提取到内存中供程序调用 ADO.NET所有数据访 ...

  6. MVC EF 增 删 改 查

    using System;using System.Collections.Generic;using System.Linq;using System.Web;//using System.Data ...

  7. python基础中的四大天王-增-删-改-查

    列表-list-[] 输入内存储存容器 发生改变通常直接变化,让我们看看下面列子 增---默认在最后添加 #append()--括号中可以是数字,可以是字符串,可以是元祖,可以是集合,可以是字典 #l ...

  8. js数组的管理[增,删,改,查]

    今天在设计表单的时候遇到对数组的一些处理的问题,比如说怎么创建一个数组,然后牵扯到数组的增删改查的方法.请看API FF: Firefox, N: Netscape, IE: Internet Exp ...

  9. day 37-8 关于mysql 的增 删 改 查 及联合列表

    1      VARCHAR : 字符串的意思 (括号内的数字代表尾数) 输入的字符串在这个范围内都行 CHAR  :字符串的意思(区别就有几位数字 必须写几位) INT   整数(位数) 输入的数字 ...

  10. list 增 删 改 查 及 公共方法

    # 热身题目:增加名字,并且按q(不论大小写)退出程序 li = ['taibai','alex','wusir','egon','女神'] while 1: username = input('&g ...

随机推荐

  1. RCP:解决Navigator快捷键不生效的问题

    自己扩展CNF之后,导航栏的删除.复制.黏贴等快捷键失效了,在网上搜索了半天,结果最终不如自己看源码. 本篇文章的主要目的不止于解决快捷键失效,更在于如何处理类似的问题,如何利用debug快速定位.这 ...

  2. ASP.NET MVC请求处理管道生命周期的19个关键环节(1-6)

    ASP.NET和ASP.NET MVC的HttpApplication请求处理管道有共同的部分和不同之处,本系列将体验ASP.NET MVC请求处理管道生命周期的19个关键环节. ①以IIS6.0为例 ...

  3. Nim教程【十二】

    排除指定符号 一般情况下使用import语句,会把一个模块内的符号都导入进来 如果你像排除特定的符号(不想让某些符号被导入进来) 可以使用except子句 就像下面这样 import mymodule ...

  4. 浅谈Excel开发:七 Excel 自定义任务窗体

    前面花了三篇文章讲解了Excel中的UDF函数,RTD函数和异步UDF函数,这些都是Excel开发中的重中之重.本文现在开始接着第二篇文章的菜单系统开始讲解Excel中可供开发的界面元素,本文要讲解的 ...

  5. html5 css3实现图中结构

    <!DOCTYPE html> <html lang="en" > <head> <title>demo</title> ...

  6. zend studio 常用快捷键

    zend studio是一款很棒的PHP语言编译器,强大的功能让很多程序员爱不释手,而快捷键更是程序员加快编写代码的利器,那么一起来看看有哪些好用的快捷键吧. 复制当前行:ctrl+alt+↓ 删除当 ...

  7. Vue的一个陷阱

    最近做项目,上线前一直有个bug,不知道是什么原因引起的, vm.$set('needVerification', true); $('.verification-button').prop('dis ...

  8. H5常用代码:适配方案5

    此方案跟方案4是同一原理,也是通过REM实现的,能单独归类出一个方案,是因为它有一定的实用价值,当你遇到追求完美,追求到一像素的UI或者产品时,那此方案将解决你的困境. 方案5主要是用来解决一像素边框 ...

  9. SqlServer 错误1053:服务并未及时响应启动或控制请求

    sqlserver 的登录用户修改成域账户后,启动不了 解决方法: 计算器管理选择管理员组 将域账户加入到管理员组即可

  10. 复杂 XML 的 序列化 反序列化

    已知.xml(再此命名default.xml)文件,请将其反序列化到一个实例对象. <?xml version="1.0" encoding="utf-8" ...