首先得到索引:

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. Software License Manager

    slmgr -ilc lenovo.xrm-ms slmgr -ipk lenovo-lenovo-lenovo-lenovo-lenovo

  2. Linux 学习 (二) 文件处理命令

    Linux达人养成计划 I 学习笔记 ls [选项] [文件或目录] -a: 显示所有文件,包括隐藏文件 -l: 显示详细信息 -d: 查看目录属性 -h: 人性化显示文件大小 -i: 显示inode ...

  3. Express学习(1) ------Express 入门

    Express 是node 第三方框架,大家都知道,框架的意义就在于能大大简化程序地开发.那么我们就看一下Express是怎么简化node程序开发的. 1,用Express写一个hello world ...

  4. 【建模应用】PLS偏最小二乘回归原理与应用

    @author:Andrew.Du 声明:本文为原创,转载请注明出处:http://www.cnblogs.com/duye/p/9031511.html,谢谢. 一.前言 1.目的: 我写这篇文章的 ...

  5. MySQL官方教程及各平台的安装教程和配置详解入口

    官方文档入口: https://dev.mysql.com/doc/ 一般选择MySQL服务器版本入口: https://dev.mysql.com/doc/refman/en/ 在右侧有版本选择: ...

  6. maven+Spring+SpringMVC+Hibernate快速搭建

    目录结构: pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns=&qu ...

  7. 在一台服务器上配置多个Tomcat的方法

    原文来自:http://blog.csdn.net/lmb55/article/details/49561669 这段时间在开发智能导航的热部署功能,需要从一台服务器去访问其它的24台服务器去进行相关 ...

  8. [Codeforces235D]Graph Game——概率与期望+基环树+容斥

    题目链接: Codeforces235D 题目大意:给出一棵基环树,并给出如下点分治过程,求点数总遍历次数的期望. 点分治过程: 1.遍历当前联通块内所有点 2.随机选择联通块内一个点删除掉 3.对新 ...

  9. 不同版本的Chrom浏览器对应的ChromDriver的版本

    附chromedriver与chrome的对应关系表: chromedriver版本 支持的Chrome版本 v2.40 v66-68 v2.39 v66-68 v2.38 v65-67 v2.37 ...

  10. Codeforces Round #542 [Alex Lopashev Thanks-Round] (Div. 2) A - D2

    A. Be Positive 链接:http://codeforces.com/contest/1130/problem/A 题意: 给一段序列,这段序列每个数都除一个d(−1e3≤d≤1e3)除完后 ...