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++代码中,使用svn版本号作为程序版本号的实现方法

    1.编写版本模板文件 #ifndef _VERSIONSVN_H_#define _VERSIONSVN_H_#define VER_REVISIONSVN $WCREV$#endif //!_VER ...

  2. 几何服务,cut功能,输入要素target(修改前)内容。

    几何服务,cut功能测试,输入要素target(修改前)内容. {"geometryType":"esriGeometryPolyline","geo ...

  3. 贪吃蛇的java代码分析(三)

    代码剖析 在上一篇文章中,我们完成了贪吃蛇部分代码的构造.回头审视我们写的代码与思路,会发现我们遗漏了一个重要的地方,那就是:贪吃蛇的自身移动.想必大家都知道,贪吃蛇自身是会自己移动的,并且会跟随你的 ...

  4. Android 使用js调用Java

    效果如: 主要用到一个接口类:MyObject package com.example.jsdemo; import android.content.Context; import android.s ...

  5. 《Linux及安全》实践3.1

    <Linux及安全>实践三 ELF格式文件分析 一.基础操作 1.查看大小端.32还是64 由此可以看出,本人实践所用到的是32位Ubuntu,数据存储采用小端法. 2.编写hello.c ...

  6. JMeter学习-035-JMeter调试工具之二---Debug PostProcessor

    前文 JMeter学习-034-JMeter调试工具之一---HTTP Mirror Server讲述了HTTP镜像服务器在调试请求入参时的实例应用.此文我们讲述另一种测试脚本调试工具的使用. 前置处 ...

  7. shell常用命令归类整理

    shell 命令整理     bash shell 含有许多功能,因此有许多可用的命令:本文档仅罗列了一些常用命令及其使用频率较高的参数.#本文档仅罗列了一些常用命令及其使用频率较高的参数.#vers ...

  8. Python之路-jQuery

    参考网址:http://jquery.cuishifeng.cn/ 1.安装环境 2.查找元素 3.操作元素 一.安装环境: 1.我们需要去官网下载jQuery,地址:http://jquery.co ...

  9. IE8文件下载启用

    在IE8的浏览器中,需要进行一些设置 Internet选项→安全→本地Intranet→自定义级别→下载→文件下载→启用 禁用迅雷下载:工具栏和扩展→迅雷下载支持→右键禁用

  10. Java多线程代码示例

    package algorithm; class Mythread extends Thread{ String name; public Mythread(String name){ this.na ...