Lucene是一个搜索类库,solr、nutch和elasticsearch都是基于Lucene。个人感觉学习高级搜索引擎应用程序之前 有必要了解Lucene。

开发环境:idea maven springboot

开始贴代码:

maven配置

 <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4..RELEASE</version>
</parent> <properties>
<java.version>1.8</java.version>
</properties> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- hot swapping, disable cache for template, enable live reload -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency> <!--Lucene-->
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-core</artifactId>
<version>7.1.</version>
</dependency> <!--中文分词器,一般分词器适用于英文分词(common)-->
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-analyzers-smartcn</artifactId>
<version>7.1.</version>
</dependency>
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-queryparser</artifactId>
<version>7.1.</version>
</dependency> <!--检索关键字高亮显示-->
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-highlighter</artifactId>
<version>7.1.</version>
</dependency>
<!--Lucene--> <dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency> </dependencies> <build>
<plugins>
<!-- Package as an executable jar/war -->
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

辅助类

public class LuceneConstants {
public static final String CONTENTS="contents";
public static final String FILE_NAME="filename";
public static final String FILE_PATH="filepath";
public static final int MAX_SEARCH = ; public static final String IndexDir ="E:\\Lucene\\Index";
public static final String DataDir ="E:\\Lucene\\Data";
public static final String ArticleDir ="E:\\Lucene\\Files\\article.txt";
}

调用Lucene

public class Indexer {

    public void addEntity() throws IOException {
Article article = new Article();
//article.setId(1);
//article.setTitle("Lucene全文检索");
//article.setContent("Lucene是apache软件基金会4 jakarta项目组的一个子项目,是一个开放源代码的全文检索引擎工具包,但它不是一个完整的全文检索引擎,而是一个全文检索引擎的架构,提供了完整的查询引擎和索引引擎,部分文本分析引擎(英文与德文两种西方语言)。");
article.setId();
article.setTitle("Solr搜索引擎");
article.setContent("Solr是基于Lucene框架的搜索莹莹程序,是一个开放源代码的全文检索引擎。"); final Path path = Paths.get(LuceneConstants.IndexDir);
Directory directory = FSDirectory.open(path);//索引存放目录 存在磁盘
//Directory RAMDirectory= new RAMDirectory();// 存在内存 Analyzer analyzer = new StandardAnalyzer();
IndexWriterConfig indexWriterConfig = new IndexWriterConfig(analyzer);
//indexWriterConfig.setOpenMode(IndexWriterConfig.OpenMode.CREATE);
indexWriterConfig.setOpenMode(IndexWriterConfig.OpenMode.APPEND); IndexWriter indexWriter = new IndexWriter(directory, indexWriterConfig);//更新或创建索引 Document document = new Document();
document.add(new TextField("id", article.getId().toString(), Field.Store.YES));
document.add(new TextField("title", article.getTitle(), Field.Store.YES));
document.add(new TextField("content", article.getContent(), Field.Store.YES)); indexWriter.addDocument(document);
indexWriter.close();
} public void addFile() throws IOException {
final Path path = Paths.get(LuceneConstants.IndexDir); Directory directory = FSDirectory.open(path);
Analyzer analyzer=new StandardAnalyzer(); IndexWriterConfig indexWriterConfig=new IndexWriterConfig(analyzer);
indexWriterConfig.setOpenMode(IndexWriterConfig.OpenMode.CREATE); IndexWriter indexWriter=new IndexWriter(directory,indexWriterConfig);
InputStreamReader isr = new InputStreamReader(new FileInputStream(LuceneConstants.ArticleDir), "GBK");//.txt文档,不设置格式会乱码
BufferedReader bufferedReader=new BufferedReader(isr); String content="";
while ((content=bufferedReader.readLine())!=null){
Document document=new Document();
document.add(new TextField("content",content,Field.Store.YES) );
indexWriter.addDocument(document);
}
bufferedReader.close();
indexWriter.close();
} public List<String> SearchFiles() throws IOException, ParseException {
String queryString = "Solr"; final Path path = Paths.get(LuceneConstants.IndexDir);
Directory directory = FSDirectory.open(path);//索引存储位置
Analyzer analyzer = new StandardAnalyzer();//分析器 //单条件
//关键词解析
//QueryParser queryParser=new QueryParser("content",analyzer);
//Query query=queryParser.parse(queryString); //多条件
Query mQuery = MultiFieldQueryParser.parse(new String[]{"Solr"},new String[]{"content"},new StandardAnalyzer()); IndexReader indexReader = DirectoryReader.open(directory);//索引阅读器
IndexSearcher indexSearcher = new IndexSearcher(indexReader);//查询 //TopDocs topDocs=indexSearcher.search(query,3);
TopDocs topDocs=indexSearcher.search(mQuery,);
long count = topDocs.totalHits;
ScoreDoc[] scoreDocs = topDocs.scoreDocs; List<String> list=new ArrayList<String>();
list.add(String.valueOf(count)); Integer cnt=; for (ScoreDoc scoreDoc : scoreDocs) {
Document document = indexSearcher.doc(scoreDoc.doc); //list.add(cnt.toString()+"-"+"相关度:"+scoreDoc.score+"-----time:"+document.get("time"));
//list.add("|||");
//list.add(cnt.toString()+"-"+document.get("content")); list.add(document.get("content"));
cnt++;
} return list;
}
}

查看运行效果

@Controller
public class LuceneController {
@RequestMapping("/add")
public String welcomepage(Map<String, Object> model) { try {
Indexer indexer = new Indexer();
indexer.addEntity(); model.put("message", "Success");
} catch (IOException ex) {
model.put("message", "Failure");
} return "welcome";
} @RequestMapping("/file")
public String fileindex(Map<String, Object> model) { try {
Indexer indexer = new Indexer();
indexer.addFile(); model.put("message", "SuccessF");
} catch (IOException ex) {
model.put("message", "FailureF");
} return "welcome";
} @RequestMapping("/search")
public String searchindex(Map<String, Object> model) { try {
Indexer indexer = new Indexer();
List<String> rlts = indexer.SearchFiles();
String message = "";
for (String str : rlts) {
message += str + " ";
}
model.put("message", message);
} catch (Exception ex) {
model.put("message", "FailureF");
} return "welcome";
} }

Lucene学习笔记1(V7.1)的更多相关文章

  1. Lucene学习笔记(更新)

    1.Lucene学习笔记 http://www.cnblogs.com/hanganglin/articles/3453415.html    

  2. Lucene学习笔记2-Lucene的CRUD(V7.1)

    在进行CRUD的时候请注意IndexWriterConfig的设置. public class IndexCRUD { "}; private String citys[]={"j ...

  3. Apache Lucene学习笔记

    Hadoop概述 Apache lucene: 全球第一个开源的全文检索引擎工具包 完整的查询引擎和搜索引擎 部分文本分析引擎 开发人员在此基础建立完整的全文检索引擎 以下为转载:http://www ...

  4. Lucene学习笔记

    师兄推荐我学习Lucene这门技术,用了两天时间,大概整理了一下相关知识点. 一.什么是Lucene Lucene即全文检索.全文检索是计算机程序通过扫描文章中的每一个词,对每一个词建立一个索引,指明 ...

  5. Lucene学习笔记: 四,Lucene索引过程分析

    对于Lucene的索引过程,除了将词(Term)写入倒排表并最终写入Lucene的索引文件外,还包括分词(Analyzer)和合并段(merge segments)的过程,本次不包括这两部分,将在以后 ...

  6. Solr学习笔记1(V7.2)

    下载压缩包http://archive.apache.org/dist/lucene/,解压后放到某一盘符下面 Windows下启动命令 :\solr-7.2.0>bin\solr.cmd st ...

  7. Lucene学习笔记:基础

    Lucence是Apache的一个全文检索引擎工具包.可以将采集的数据存储到索引库中,然后在根据查询条件从索引库中取出结果.索引库可以存在内存中或者存在硬盘上. 本文主要是参考了这篇博客进行学习的,原 ...

  8. Lucene学习笔记: 五,Lucene搜索过程解析

    一.Lucene搜索过程总论 搜索的过程总的来说就是将词典及倒排表信息从索引中读出来,根据用户输入的查询语句合并倒排表,得到结果文档集并对文档进行打分的过程. 其可用如下图示: 总共包括以下几个过程: ...

  9. lucene学习笔记:三,Lucene的索引文件格式

    Lucene的索引里面存了些什么,如何存放的,也即Lucene的索引文件格式,是读懂Lucene源代码的一把钥匙. 当我们真正进入到Lucene源代码之中的时候,我们会发现: Lucene的索引过程, ...

随机推荐

  1. K:java 断言 assert 初步使用:断言开启、断言使用

    @转自天地悠悠的个人博客 主要总结一下在eclipse中如何使用断言. (一)首先明确: java断言Assert是jdk1.4引入的. jvm 断言默认是关闭的. 断言是可以局部开启的,如:父类禁止 ...

  2. Fiddler捕获localhost的网站

    Fiddler如何捕获localhost的网站?在hosts文件中加入127.0.0.1  localsite这样也可以被捕获到.

  3. 利用lsof恢复进程占用的文件

    说明:经常会遇到这种情况,没有使用正确的方式清理进程占用的文件,比如日志.导致空间并没有释放.也有的时候需要恢复进程占用的文件. 解决方式 lsof |grep del # 找出自己要恢复的文件名称. ...

  4. Python装饰器的解包装(unwrap)

    在Python 3.4 中,新增一个方法unwrap,用于将被装饰的函数,逐层进行解包装. inspect.unwrap(func, *, stop=None) unwrap方法接受两个参数:func ...

  5. MicroPython-GPRS教程之TPYBoardv702GPRS功能测试

    一.什么是TPYBoardV702 TPYBoardV702是目前市面上唯一支持通信通信功能的MicroPython开发板:支持Python3.0及以上版本直接运行.支持GPS+北斗双模通信.GPRS ...

  6. 最新版Solr 7.2安装配置

    Solr是一个独立的企业级搜索应用服务器,它对外提供类似于Web-service的API接口.用户可以通过http请求,向搜索引擎服务器提交一定格式的XML文件,生成索引:也可以通过Http Get操 ...

  7. python3之装饰器

    1.装饰器 装饰器本质上是一个python函数,它可以让其他函数在不需要做任何代码变动的前提下增加额外功能,装饰器的返回值也是一个函数对象.它经常用于有切面需求的场景,比如:插入日志.性能测试.事务处 ...

  8. linux搭建SS服务

    基本准备: 购买主机:www.virmach.com LINUX系统操作经验:vim , apt-get 等命令的使用 putty.exe连接ssh工具的使用 开始 使用putty连接上去,并输入密码 ...

  9. HTML知识点总结之div、section标签

    div元素 div是块级元素,相当于一个容器,在语义上不代表任何特定类型的内容.主要用作大的框架布局,也就是说网页的骨架主要通过div来架设的,而网页的血肉则是有span.p或者ul等元素完成. se ...

  10. (5编译使用最新opencv)从零开始的嵌入式图像图像处理(PI+QT+OpenCV)实战演练

    从零开始的嵌入式图像图像处理(PI+QT+OpenCV)实战演练 1综述http://www.cnblogs.com/jsxyhelu/p/7907241.html 2环境架设http://www.c ...