首先得到索引:

package com.wp.util;

import java.io.File;
import java.io.FileReader;
import java.nio.file.Paths; 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.TextField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory; public class Indexer { private IndexWriter writer; // 写索引实例 /**
* 构造方法 实例化IndexWriter
*
* @param indexDir
* @throws Exception
*/
public Indexer(String indexDir) throws Exception {
Directory dir = FSDirectory.open(Paths.get(indexDir));// 根据路径获取存储索引的目录
Analyzer analyzer = new StandardAnalyzer(); // 这里用了多态,StandardAnalyzer是一个标准分词器,
IndexWriterConfig iwc = new IndexWriterConfig(analyzer);//将分词器加入到索引中
writer = new IndexWriter(dir, iwc);
} /**
* 关闭写索引
*
* @throws Exception
*/
public void close() throws Exception {
writer.close();
} /**
* 索引指定目录的所有文件
*
* @param dataDir
* @throws Exception
*/
public int index(String dataDir) throws Exception {
File[] files = new File(dataDir).listFiles();//得到目录下的所有文件
for (File f : files) {
indexFile(f);
}
return writer.numDocs();
} /**
* 索引指定文件
*
* @param f
*/
private void indexFile(File f) throws Exception {
// 关于f.getCanonicalPath()查看http://www.blogjava.net/dreamstone/archive/2007/08/08/134968.html
System.out.println("索引文件:" + f.getCanonicalPath());//得到绝对路径
Document doc = getDocument(f);
writer.addDocument(doc);
} /**
* 获取文档,文档里再设置每个字段
*
* @param f
*/
private Document getDocument(File f) throws Exception {
Document doc = new Document();//创建文档
doc.add(new TextField("contents", new FileReader(f)));//以文件流的形式读取文件内容
doc.add(new TextField("fileName", f.getName(), Field.Store.YES));//Field.Store.YES表示将属性存入内存中
doc.add(new TextField("fullPath", f.getCanonicalPath(),Field.Store.YES));//存入内存中
return doc;
} public static void main(String[] args) {
String indexDir = "D:\\lucene\\luceneIndex";
String dataDir = "D:\\lucene\\data";
Indexer indexer = null;
int numIndexed = 0;
long start = System.currentTimeMillis();
try {
indexer = new Indexer(indexDir);//创建索引
numIndexed = indexer.index(dataDir);//索引指定目录的所有文件
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
indexer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
long end = System.currentTimeMillis();
System.out.println("索引:" + numIndexed + " 个文件 花费了" + (end - start)
+ " 毫秒");
}
}

增加的知识:

getPath():

返回的是定义时的路径,可能是相对路径,也可能是绝对路径,这个取决于定义时用的是相对路径还是绝对路径。如果定义时用的是绝对路径,那么使用getPath()返回的结果跟用getAbsolutePath()返回的结果一样

getAbsolutePath():

返回的是定义时的路径对应的相对路径,但不会处理“.”和“..”的情况

getCanonicalPath():

返回的是规范化的绝对路径,相当于将getAbsolutePath()中的“.”和“..”解析成对应的正确的路径

搜索:

package com.wp.util;

import java.nio.file.Paths;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
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.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test; public class SearchTest { private Directory dir;
private IndexReader reader;
private IndexSearcher is; @Before
public void setUp() throws Exception {
dir = FSDirectory.open(Paths.get("D:\\lucene\\luceneIndex"));// 得到存储索引的目录
reader = DirectoryReader.open(dir);// 读取索引
is = new IndexSearcher(reader);// //创建索引搜索
} @After
public void tearDown() throws Exception {
reader.close();
} /**
* 对特定项搜索(只能是指定的字符串,而不是其中的字母)
*
* @throws Exception
*/
@Test
public void testTermQuery() throws Exception {
String searchField = "contents";
String q = "particular";
Term t = new Term(searchField, q);// 查询contents中的particular字符
Query query = new TermQuery(t);// 对特定字符查询
TopDocs hits = is.search(query, 10);// 得到查询的最前面10条数据
System.out.println("匹配 '" + q + "',总共查询到" + hits.totalHits + "个文档");
for (ScoreDoc scoreDoc : hits.scoreDocs) {
Document doc = is.doc(scoreDoc.doc);// 得到查询到的得分文档个数
System.out.println(doc.get("fullPath"));
}
} /**
* 解析查询表达式
*
* @throws Exception
*/
@Test
public void testQueryParser() throws Exception {
Analyzer analyzer = new StandardAnalyzer(); // 标准分词器
String searchField = "contents";
// String q = "particular AND SA";//表示查询都: 注意AND要大写
// String q = "particular or a";// 表示查询或者
String q = "particular~";// ~符号表示查询相近的
QueryParser parser = new QueryParser(searchField, analyzer);
Query query = parser.parse(q);// 进行解析
TopDocs hits = is.search(query, 100);
System.out.println("匹配 " + q + "查询到" + hits.totalHits + "个记录");
for (ScoreDoc scoreDoc : hits.scoreDocs) {
Document doc = is.doc(scoreDoc.doc);
System.out.println(doc.get("fullPath"));
}
}
}

lucene的普通搜索(二)的更多相关文章

  1. Apache Solr采用Java开发、基于Lucene的全文搜索服务器

    http://docs.spring.io/spring-data/solr/ 首先介绍一下solr: Apache Solr (读音: SOLer) 是一个开源.高性能.采用Java开发.基于Luc ...

  2. Apache Lucene(全文检索引擎)—搜索

    目录 返回目录:http://www.cnblogs.com/hanyinglong/p/5464604.html 本项目Demo已上传GitHub,欢迎大家fork下载学习:https://gith ...

  3. lintcode:搜索二维矩阵II

    题目 搜索二维矩阵 II 写出一个高效的算法来搜索m×n矩阵中的值,返回这个值出现的次数. 这个矩阵具有以下特性: 每行中的整数从左到右是排序的. 每一列的整数从上到下是排序的. 在每一行或每一列中没 ...

  4. lintcode :搜索二维矩阵

    题目: 搜索二维矩阵 写出一个高效的算法来搜索 m × n矩阵中的值. 这个矩阵具有以下特性: 每行中的整数从左到右是排序的. 每行的第一个数大于上一行的最后一个整数. 样例 考虑下列矩阵: [ [1 ...

  5. Lucene的其他搜索(三)

    生成索引: package com.wp.search; import java.nio.file.Paths; import org.apache.lucene.analysis.Analyzer; ...

  6. 算法进阶面试题05——树形dp解决步骤、返回最大搜索二叉子树的大小、二叉树最远两节点的距离、晚会最大活跃度、手撕缓存结构LRU

    接着第四课的内容,加入部分第五课的内容,主要介绍树形dp和LRU 第一题: 给定一棵二叉树的头节点head,请返回最大搜索二叉子树的大小 二叉树的套路 统一处理逻辑:假设以每个节点为头的这棵树,他的最 ...

  7. 基于 Lucene 的桌面文件搜索

    开源2010年,自己在学习 Lucene 时开发的一款桌面文件搜索工具,这么多年过去了,代码一直静静存放在自己的硬盘上,与其让其沉睡,不如分享出来. 这款工具带有明显的模仿 Everything 的痕 ...

  8. LintCode-38.搜索二维矩阵 II

    搜索二维矩阵 II 写出一个高效的算法来搜索m×n矩阵中的值,返回这个值出现的次数. 这个矩阵具有以下特性: 每行中的整数从左到右是排序的. 每一列的整数从上到下是排序的. 在每一行或每一列中没有重复 ...

  9. LeetCode74.搜索二维矩阵

    74.搜索二维矩阵 描述 编写一个高效的算法来判断 m x n 矩阵中,是否存在一个目标值.该矩阵具有如下特性: 每行中的整数从左到右按升序排列. 每行的第一个整数大于前一行的最后一个整数. 示例 示 ...

随机推荐

  1. Pulse-per-second (PPS) Signal Interfacing

    Some radio clocks and related timekeeping gear have a pulse-per-second (PPS) signal that can be used ...

  2. Xamarin 简化的Android密钥库签名

    安装 开始使用这个新工具不容易.在Visual Studio 2017(即将推出VS 2015),只需转到工具 - >扩展和更新,并搜索“密钥库”来查找扩展名. 下载后,只需重新启动Visual ...

  3. 使用js主函数的原因是等文档加载完了才给里面的元素添加东西 如果不使用主函数则文档加载时候无法找到元素则不能成功给元素添加事件

    使用js主函数的原因是等文档加载完了才给里面的元素添加东西 如果不使用主函数则文档加载时候无法找到元素则不能成功给元素添加事件

  4. React 学习(四) ---- 生命周期函数

    现在我们能修改状态,页面可以进行交互了,但是还有一种状态改变没有解决,那就是倒计时效果,时间一直在变化,组件状态也一直在改变,但我们什么都没有做,如果要实现这样的效果,需要怎么处理? 我们都知道,改变 ...

  5. CSS初步学习

    1.选择器: 如果你要在HTML元素中设置CSS样式,你需要在元素中设置"id" 和 "class"选择器. id 选择器 id 选择器可以为标有特定 id 的 ...

  6. Codeforces379 F. New Year Tree

    Codeforces题号:#379F 出处: Codeforces 主要算法:LCA+树的直径 难度:4.4 思路分析: 给出q个操作,每次在一个节点上接上两个叶子.每一次询问树的直径. 暴力做法:每 ...

  7. luogu P3128 [USACO15DEC]最大流Max Flow (树上差分)

    题目描述 Farmer John has installed a new system of N-1N−1 pipes to transport milk between the NN stalls ...

  8. day3 python简介 IDE选择

    优势趋势基于c语言.c语言是编译底层语言,c跨平台需要重新编译,pyh可以直接使用c的库文件,比起c有绝对的开发效率目前为全球语言使用频率为第四名,第一java.从几年前第8名已超越php第6名. 擅 ...

  9. python学习日记(文件操作练习题)

    登录注册(三次机会) name = input('请注册姓名:') password = input('请注册密码:') with open('log',mode='w',encoding='utf- ...

  10. 【bzoj3456】城市规划(多项式求逆+dp)

    Description 求\(~n~\)个点组成的有标号无向连通图的个数.\(~1 \leq n \leq 13 \times 10 ^ 4~\). Solution 这道题的弱化版是poj1737, ...