Lucene的基本应用
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List; 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.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.QueryParser;
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.util.Version;
import org.junit.Test; import cn.itcast._domain.Article; public class HelloWorld { private static Directory directory; // 索引库文件夹
private static Analyzer analyzer; // 分词器 static {
try {
directory = FSDirectory.open(new File("./indexDir"));
analyzer = new StandardAnalyzer(Version.LUCENE_30);
} catch (IOException e) {
throw new RuntimeException(e);
}
} // 建立索引
@Test
public void testCreateIndex() throws Exception {
// 准备数据
Article article = new Article();
article.setId(1);
article.setTitle("准备Lucene的开发环境");
article.setContent("假设信息检索系统在用户发出了检索请求后再去互联网上找答案,根本无法在有限的时间内返回结果。"); // 放到索引库中
// 1, 把Article转为Document
Document doc = new Document();
String idStr = article.getId().toString();
doc.add(new Field("id", idStr, Store.YES, Index.NOT_ANALYZED));
doc.add(new Field("title", article.getTitle(), Store.YES, Index.ANALYZED));
doc.add(new Field("content", article.getContent(), Store.NO, Index.ANALYZED)); // 2, 把Document放到索引库中
IndexWriter indexWriter = new IndexWriter(directory, analyzer, MaxFieldLength.UNLIMITED);
indexWriter.addDocument(doc);
indexWriter.close();
} // 搜索
@Test
public void testSearch() throws Exception {
// 准备查询条件
String queryString = "lucene";
// String queryString = "hibernate"; // 运行搜索
List<Article> list = new ArrayList<Article>(); // ========================================================================================== // 1,把查询字符串转为Query对象(默认仅仅从title中查询)
QueryParser queryParser = new QueryParser(Version.LUCENE_30, "title", analyzer);
Query query = queryParser.parse(queryString); // 2,运行查询,得到中间结果
IndexSearcher indexSearcher = new IndexSearcher(directory); // 指定所用的索引库
TopDocs topDocs = indexSearcher.search(query, 100); // 最多返回前n条结果 int count = topDocs.totalHits;
ScoreDoc[] scoreDocs = topDocs.scoreDocs; // 3,处理结果
for (int i = 0; i < scoreDocs.length; i++) {
ScoreDoc scoreDoc = scoreDocs[i];
float score = scoreDoc.score; // 相关度得分
int docId = scoreDoc.doc; // Document的内部编号 // 依据编号拿到Document数据
Document doc = indexSearcher.doc(docId); // 把Document转为Article
String idStr = doc.getField("id").toString(); //doc.get("id");
String title = doc.get("title");
String content = doc.get("content"); // 等价于 doc.getField("content").stringValue(); Article article = new Article();
article.setId(Integer.parseInt(idStr));
article.setTitle(title);
article.setContent(content); list.add(article);
}
indexSearcher.close(); // ========================================================================================== // 显示结果
System.out.println("总结果数:" + list.size());
for (Article a : list) {
System.out.println("------------------------------");
System.out.println("id = " + a.getId());
System.out.println("title = " + a.getTitle());
System.out.println("content = " + a.getContent());
}
}
}
public class Article {
private Integer id;
private String title;
private String content;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
Lucene的基本应用的更多相关文章
- lucene 基础知识点
部分知识点的梳理,参考<lucene实战>及网络资料 1.基本概念 lucence 可以认为分为两大组件: 1)索引组件 a.内容获取:即将原始的内容材料,可以是数据库.网站(爬虫).文本 ...
- 用lucene替代mysql读库的尝试
采用lucene对mysql中的表建索引,并替代全文检索操作. 备注:代码临时梳理很粗糙,后续修改. import java.io.File; import java.io.IOException; ...
- Lucene的评分(score)机制研究
首先,需要学习Lucene的评分计算公式—— 分值计算方式为查询语句q中每个项t与文档d的匹配分值之和,当然还有权重的因素.其中每一项的意思如下表所示: 表3.5 评分公式中的因子 评分因子 描 述 ...
- Lucene的分析资料【转】
Lucene 源码剖析 1 目录 2 Lucene是什么 2.1.1 强大特性 2.1.2 API组成- 2.1.3 Hello World! 2.1.4 Lucene roadmap 3 索引文件结 ...
- Lucene提供的条件判断查询
第一.按词条搜索 - TermQuery query = new TermQuery(new Term("name","word1"));hits = sear ...
- Lucene 单域多条件查询
在Lucene 中 BooleanClause用于表示布尔查询子句关系的类,包括:BooleanClause.Occur.MUST表示and,BooleanClause.Occur.MUST_NOT表 ...
- lucene自定义过滤器
先介绍下查询与过滤的区别和联系,其实查询(各种Query)和过滤(各种Filter)之间非常相似,可以这样说只要用Query能完成的事,用过滤也都可以完成,它们之间可以相互转换,最大的区别就是使用过滤 ...
- lucene+IKAnalyzer实现中文纯文本检索系统
首先IntelliJ IDEA中搭建Maven项目(web):spring+SpringMVC+Lucene+IKAnalyzer spring+SpringMVC搭建项目可以参考我的博客 整合Luc ...
- 全文检索解决方案(lucene工具类以及sphinx相关资料)
介绍两种全文检索的技术. 1. lucene+ 中文分词(IK) 关于lucene的原理,在这里可以得到很好的学习. http://www.blogjava.net/zhyiwww/archive/ ...
- MySQL和Lucene索引对比分析
MySQL和Lucene都可以对数据构建索引并通过索引查询数据,一个是关系型数据库,一个是构建搜索引擎(Solr.ElasticSearch)的核心类库.两者的索引(index)有什么区别呢?以前写过 ...
随机推荐
- [python][oldboy]字符串 format
#coding=utf8 def format(self, *args, **kwargs): # known special case of str.format """ ...
- Codeforces Round #470 (rated, Div. 2, based on VK Cup 2018 Round 1)
A. Protect Sheep time limit per test 1 second memory limit per test 256 megabytes input standard inp ...
- NuGet安装本地包命令行
尝试安装本地的NuGet包. 键入 "get-help NuGet" 可查看所有可用的 NuGet 命令. install-package Polly.Net40Async-Sig ...
- POJ 2355 Railway tickets
Railway tickets Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 2472 Accepted: 865 De ...
- ACM程序设计选修课——1041: XX's easy problem(神烦的多次字符串重定向处理)
1041: XX's easy problem Time Limit: 1 Sec Memory Limit: 128 MB Submit: 41 Solved: 7 [Submit][Statu ...
- Mondriaan's Dream(poj 2411)
题意:在n*m的方格里铺1*2的骨牌,有多少种方案 /* 第一次做插头DP,感觉和状压差不多. 这道题是利用上一行的状态来更新下一行的状态. 1代表上一行这个位置填了一个竖的(即本行可以填): 0代表 ...
- poj 1912 A highway and the seven dwarfs
A highway and the seven dwarfs Time Limit: 8000MS Memory Limit: 30000K Total Submissions: 2622 A ...
- 【CF1028C】Rectangles(线段树)
题意: n<=1e5,abs(x[i]),abs(y[i]<=1e9 思路:这是正解 离散后线段树强打,数据结构越学越傻 #include<cstdio> #include&l ...
- 标准C程序设计七---77
Linux应用 编程深入 语言编程 标准C程序设计七---经典C11程序设计 以下内容为阅读: <标准C程序设计>(第7版) 作者 ...
- AC日记——【模板】最小费用最大流 P3381
题目描述 如题,给出一个网络图,以及其源点和汇点,每条边已知其最大流量和单位流量费用,求出其网络最大流和在最大流情况下的最小费用. 输入输出格式 输入格式: 第一行包含四个正整数N.M.S.T,分别表 ...