package com.ljq.one;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.NumberTools;
import org.apache.lucene.document.Field.Index;
import org.apache.lucene.document.Field.Store;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriter.MaxFieldLength;
import org.apache.lucene.queryParser.MultiFieldQueryParser;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.Filter;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.RAMDirectory;
import org.junit.Test;

public class DirectoryTest {
// 数据源路径
String dspath = "E:/workspace/mylucene/lucenes/IndexWriter addDocument's a javadoc .txt";
//存放索引文件的位置,即索引库
String indexpath = "E:/workspace/mylucene/luceneIndex";
//分词器
Analyzer analyzer = new StandardAnalyzer();

/**
* 创建索引,会抛异常,因为没对索引库进行保存
*
* IndexWriter 用来操作(增、删、改)索引库的
*/
@Test
public void createIndex() throws Exception {
//Directory dir=FSDirectory.getDirectory(indexpath);
//内存存储:优点速度快,缺点程序退出数据就没了,所以记得程序退出时保存索引库,已FSDirectory结合使用
//由于此处只暂时保存在内存中,程序退出时没进行索引库保存,因此在搜索时程序会报错
Directory dir=new RAMDirectory();
File file = new File(dspath);
//Document存放经过组织后的数据源,只有转换为Document对象才可以被索引和搜索到
Document doc = new Document();
//文件名称
doc.add(new Field("name", file.getName(), Store.YES, Index.ANALYZED));
//检索到的内容
doc.add(new Field("content", readFileContent(file), Store.YES, Index.ANALYZED));
//文件大小
doc.add(new Field("size", NumberTools.longToString(file.length()),
Store.YES, Index.NOT_ANALYZED));
//检索到的文件位置
doc.add(new Field("path", file.getAbsolutePath(), Store.YES, Index.NOT_ANALYZED));

// 建立索引
//第一种方式
//IndexWriter indexWriter = new IndexWriter(indexpath, analyzer, MaxFieldLength.LIMITED);
//第二种方式
IndexWriter indexWriter = new IndexWriter(dir, analyzer, MaxFieldLength.LIMITED);
indexWriter.addDocument(doc);
indexWriter.close();
}

/**
* 创建索引(推荐)
*
* IndexWriter 用来操作(增、删、改)索引库的
*/
@Test
public void createIndex2() throws Exception {
Directory fsDir = FSDirectory.getDirectory(indexpath);
//1、启动时读取
Directory ramDir = new RAMDirectory(fsDir);

// 运行程序时操作ramDir
IndexWriter ramIndexWriter = new IndexWriter(ramDir, analyzer, MaxFieldLength.LIMITED);

//数据源
File file = new File(dspath);
// 添加 Document
Document doc = new Document();
//文件名称
doc.add(new Field("name", file.getName(), Store.YES, Index.ANALYZED));
//检索到的内容
doc.add(new Field("content", readFileContent(file), Store.YES, Index.ANALYZED));
//文件大小
doc.add(new Field("size", NumberTools.longToString(file.length()), Store.YES, Index.NOT_ANALYZED));
//检索到的文件位置
doc.add(new Field("path", file.getAbsolutePath(), Store.YES, Index.NOT_ANALYZED));
ramIndexWriter.addDocument(doc);
ramIndexWriter.close();

//2、退出时保存
IndexWriter fsIndexWriter = new IndexWriter(fsDir, analyzer, true, MaxFieldLength.LIMITED);
fsIndexWriter.addIndexesNoOptimize(new Directory[]{ramDir});

// 优化操作
fsIndexWriter.commit();
fsIndexWriter.optimize();

fsIndexWriter.close();
}

/**
* 优化操作
*
* @throws Exception
*/
@Test
public void createIndex3() throws Exception{
Directory fsDir = FSDirectory.getDirectory(indexpath);
IndexWriter fsIndexWriter = new IndexWriter(fsDir, analyzer, MaxFieldLength.LIMITED);

fsIndexWriter.optimize();
fsIndexWriter.close();
}

/**
* 搜索
*
* IndexSearcher 用来在索引库中进行查询
*/
@Test
public void search() throws Exception {
//请求字段
//String queryString = "document";
String queryString = "adddocument";

// 1,把要搜索的文本解析为 Query
String[] fields = { "name", "content" };
QueryParser queryParser = new MultiFieldQueryParser(fields, analyzer);
Query query = queryParser.parse(queryString);

// 2,进行查询,从索引库中查找
IndexSearcher indexSearcher = new IndexSearcher(indexpath);
Filter filter = null;
TopDocs topDocs = indexSearcher.search(query, filter, 10000);
System.out.println("总共有【" + topDocs.totalHits + "】条匹配结果");

// 3,打印结果
for (ScoreDoc scoreDoc : topDocs.scoreDocs) {
// 文档内部编号
int index = scoreDoc.doc;
// 根据编号取出相应的文档
Document doc = indexSearcher.doc(index);
System.out.println("------------------------------");
System.out.println("name = " + doc.get("name"));
System.out.println("content = " + doc.get("content"));
System.out.println("size = " + NumberTools.stringToLong(doc.get("size")));
System.out.println("path = " + doc.get("path"));
}
}

/**
* 读取文件内容
*/
public static String readFileContent(File file) {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
StringBuffer content = new StringBuffer();
for (String line = null; (line = reader.readLine()) != null;) {
content.append(line).append("\n");
}
reader.close();
return content.toString();
} catch (Exception e) {
throw new RuntimeException(e);
}
}

}

lucene中FSDirectory、RAMDirectory的用法的更多相关文章

  1. lucene中Field简析

    http://blog.csdn.net/zhaoxiao2008/article/details/14180019 先看一段lucene3代码 Document doc = new Document ...

  2. 【Lucene3.6.2入门系列】第03节_简述Lucene中常见的搜索功能

    package com.jadyer.lucene; import java.io.File; import java.io.IOException; import java.text.SimpleD ...

  3. lucene 中关于Store.YES 关于Store.NO的解释

    总算搞明白 lucene 中关于Store.YES  关于Store.NO的解释了 一直对Lucene Store.YES不太理解,网上多数的说法是存储字段,NO为不存储. 这样的解释有点郁闷:字面意 ...

  4. Lucene 中自定义排序的实现

    使用Lucene来搜索内容,搜索结果的显示顺序当然是比较重要的.Lucene中Build-in的几个排序定义在大多数情况下是不适合我们使用的.要适合自己的应用程序的场景,就只能自定义排序功能,本节我们 ...

  5. lucene中的IndexWriter.setMaxFieldLength()

    lucene中的IndexWriter.setMaxFieldLength() 老版本的Lucene中,IndexWriter的maxFieldLength是指一个索引中的最大的Field个数. 这个 ...

  6. lucene中创建索引库

    package com.hope.lucene;import org.apache.commons.io.FileUtils;import org.apache.lucene.document.Doc ...

  7. Java中的Socket的用法

                                   Java中的Socket的用法 Java中的Socket分为普通的Socket和NioSocket. 普通Socket的用法 Java中的 ...

  8. ecshop中foreach的详细用法归纳

    ec模版中foreach的常见用法. foreach 语法: 假如后台:$smarty->assign('test',$test); {foreach from=$test item=list ...

  9. matlab中patch函数的用法

    http://blog.sina.com.cn/s/blog_707b64550100z1nz.html matlab中patch函数的用法——emily (2011-11-18 17:20:33) ...

随机推荐

  1. c++利用循环数组建立FIFO模板队列

    可直接编译运行,其中status()方法效果如图: #include <iostream> using std::cout; template<typename T> clas ...

  2. 使用nginx和iptables做访问权限控制(IP和MAC)

    之前配置的服务器,相当于对整个内网都是公开的 而且,除了可以通过80端口的nginx来间接访问各项服务,也可以绕过nginx,直接ip地址加端口访问对应服务 这是不对的啊,所以我们要做一些限制 因为只 ...

  3. 那些年一起用过的iOS开发利器之Parse

    阅读此文章需要对Objective-C和iOS有一定的了解,完全没有基础的朋友请先阅读<让不懂编程的人爱上iPhone开发>系列教程. 什么是后台服务(back-end service)? ...

  4. 手机版本高于xcode,xcode的快速升级

    iPhone手机更新版本,xcode未更新时,不能真机测试 在xcode show in finder里面添加最新iPhone 版本 重启xcode即可 真机测试

  5. Javascript实现页面跳转的几种方式

    概述 相信很多Web开发者都知道,在开发Web程序的时候,对于页面之间的跳转,有很多种,但是有效的跳转则事半功倍,下面就是我在平时的开发过程中所用到的一些JavaScript跳转方式,拿出和大家共享一 ...

  6. Android 保存图片到SQLite

    [转:原文] Resources res = getResources(); Bitmap bmp = BitmapFactory.decodeResource(res, R.drawable.ico ...

  7. 【转】如何把Json格式字符写进text文件中

    http://www.cnblogs.com/insus/p/4306640.html http://json2csharp.chahuo.com/ 本篇一步一步学习怎样把显示于网页的json格式的字 ...

  8. [skill] C++ delete VS delete []

    delete 用来删除 new 返回的对象. 先调用对象的析构,然后释放指针指向的内存. delete[] 用来删除 new [] 返回的对象. 先调用数组中每一个对象的析构,然后释放指针指向的内存.

  9. (转)微信小程序破解IDE

    1.IDE下载 微信web开发者工具,本人是用的windows 10 x64系统,用到以下两个版本的IDE安装工具与一个破解工具包: wechat_web_devtools_0.7.0_x64.exe ...

  10. vert.x学习(一),开篇之hello world

    今天决定学习下vert.x这个框架,记录下学习笔记. 下面列下我的开发环境: Java版本 1.8 maven版本 3.3 IDEA版本 2016 在idea中使用vert.x不用下载或安装其他东西了 ...