package com.lucenedemo;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.*;
import java.util.*;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.Term;
import org.apache.lucene.index.TermDocs;
import org.apache.lucene.queryParser.MultiFieldQueryParser;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.Hits;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.RangeQuery;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.Searcher;
import org.apache.lucene.search.Sort;
import org.apache.lucene.search.SortField;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocCollector;
/*
* @author zhaozhi3758
* 为数据库建立索引并查询
*/
public class SearchDb {
private ArrayList dbList = new ArrayList();
private String INDEX_DIR = "f:/index";
/**
* 获取数据库数据
*
* @return
*/
@SuppressWarnings("finally")
public void getResults() {
ResultSet rs = null;
Statement stmt = null;
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");// 加载驱动
// new oracle.jdbc.driver.OracleDriver();
String url = "jdbc:mysql://localhost/libraryv1";
conn = DriverManager.getConnection(url, "root", "123");// 建立连接
stmt = conn.createStatement();
rs = stmt.executeQuery("select * from reader");// 发送执行,获得结果集
while (rs.next()) {// 遍历结果
HashMap map = new HashMap();
map.put("name", rs.getString(2));
map.put("vocation", rs.getString(5));
map.put("date", rs.getString(6));
this.dbList.add(map);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (rs != null) {// 关闭连接释放资源
rs.close();
rs = null;
}
if (stmt != null) {
stmt.close();
stmt = null;
}
if (conn != null) {
conn.close();
conn = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* 创建索引
*/
public void indexDocs() {
if (this.dbList.size() <= 0)
return;
try {
IndexWriter writer = new IndexWriter(this.INDEX_DIR,
new StandardAnalyzer(), true);
createIndex(writer);
System.out.println("正在优化...");
writer.optimize();
writer.close();
} catch (IOException e) {
System.out.println(" caught a " + e.getClass()
+ "\n with message: " + e.getMessage());
}
}
public void createIndex(IndexWriter writer) {
HashMap map = new HashMap();
for (Iterator it = this.dbList.iterator(); it.hasNext();) {
map = (HashMap)it.next();
Document doc = new Document();//必须放在循环中
//System.out.println("-->" + map.get("date").toString());
doc.add(new Field("name", map.get("name").toString(),Field.Store.YES, Field.Index.TOKENIZED));
doc.add(new Field("vocation", map.get("vocation").toString(),Field.Store.YES, Field.Index.TOKENIZED));
doc.add(new Field("date", map.get("date").toString(),Field.Store.YES, Field.Index.TOKENIZED));
//增加共同域
doc.add(new Field("all", "0",Field.Store.YES, Field.Index.TOKENIZED));
try {
writer.addDocument(doc);//添加到索引器writer
} catch (CorruptIndexException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 结果遍历
* @param hits
* @param key
* @throws Exception
*/
public static void printResult(Hits hits, String key,int num) throws Exception {
System.out.println("查找 \"" + key + "\" :");
if (hits != null) {
if (hits.length() == 0) {
System.out.println("没有找到任何结果");
} else {
System.out.println("找到" + hits.length() + "个结果");
for (int i = 0; i < hits.length(); i++) {
Document doc = hits.doc(i);
System.out.println("姓名"+num+":" + doc.get("name"));
System.out.println("职业"+num+":"+ doc.get("vocation"));
}
}
}
}
/**
* 遍历索引[方式一:按词条搜索]
* 注意:字段值是区分大小写的,因此在查询时必须注意大小写的匹配
*/
public void search_mod1(String type, String keyword)
throws CorruptIndexException, IOException, ParseException {
IndexSearcher searcher = new IndexSearcher(this.INDEX_DIR);
Term term = new Term(type,keyword);
//Query query=new TermQuery(term);最常用,然后构造hits保存检索结果
TermDocs docs = searcher.getIndexReader().termDocs(term);
//System.out.println("count:"+docs.freq());
while (docs.next()) {
Document doc = searcher.doc(docs.doc());
System.out.println("姓名1:" + doc.get("name"));
System.out.println("职业1:" + doc.get("vocation"));
}
if (searcher != null)searcher.close();
}
/**
* 遍历索引[方式二]
* @param type
* @param keyword
* @throws Exception
*/
public void search_mod2(String type, String keyword) throws Exception{
int count=50;//取前50条
Searcher searcher = new IndexSearcher(INDEX_DIR);
Query query = new QueryParser(type, new StandardAnalyzer()).parse(keyword);
TopDocCollector collector = new TopDocCollector(count);
searcher.search(query, collector);
ScoreDoc[] hits = collector.topDocs().scoreDocs;
// System.out.println("共查找到结果:"+hits.length);
for (int i = 0; i < hits.length; i++) {
int docId = hits[i].doc;
Document doc = searcher.doc(docId);
//System.out.println("Title:"+doc.get("title"));
System.out.println("姓名2:"+doc.get("name"));
System.out.println("职业2:"+doc.get("vocation"));
}
if (searcher != null)searcher.close();
}
/**
* 遍历索引[方式三]
* @param type
* @param keyword
* @throws Exception
*/
public void search_mod3(String type, String keyword)throws Exception{
Searcher searcher = new IndexSearcher(INDEX_DIR);
Query query = new QueryParser(type, new StandardAnalyzer()).parse(keyword);
Hits hits=searcher.search(query);
for(int i=0;i<hits.length();i++){
Document doc=hits.doc(i);
System.out.println("姓名3:"+doc.get("name"));
System.out.println("职业3:"+doc.get("vocation"));
}
if (searcher != null)searcher.close();
}
/**
* 遍历索引[方式四:与或搜索]
*/
public void search_mod4()throws Exception{
Query query1 = null;
Query query2 = null;
BooleanQuery query = new BooleanQuery();// 构造一个布尔查询
Hits hits = null;
Searcher searcher = new IndexSearcher(INDEX_DIR);
query1 = new TermQuery(new Term("name","赵"));
query2 = new TermQuery(new Term("vocation","教"));
// 添加两个子查询[下面两个子句为或的关系]
//MUST、SHOULD、MUST_NOT表示与、或、非
query.add(query1,BooleanClause.Occur.SHOULD);
query.add(query2,BooleanClause.Occur.SHOULD);
hits = searcher.search(query);
printResult(hits, "赵和教",4);
}
/**
* 遍历索引[方式五:在某一范围内搜索]
* @throws Exception
*/
public void search_mod5()throws Exception{
RangeQuery query = null;
Hits hits = null;
Searcher searcher = new IndexSearcher(INDEX_DIR);
//当第二的参数为null时,后边界无限
query = new RangeQuery(new Term("date","1985-04-05"),
new Term("date","1988-05-02"), true);//true包括边界
hits = searcher.search(query);
printResult(hits, "1985-04-05~1988-05-02",5);
}
/**
* 遍历索引[方式六:多域搜索]
* @throws Exception
*/
public void search_mod6()throws Exception{
Hits hits = null;
Searcher searcher = new IndexSearcher(INDEX_DIR);
//指定或的关系
BooleanClause.Occur[] flags = new BooleanClause.Occur[] {
BooleanClause.Occur.SHOULD, BooleanClause.Occur.SHOULD };
Query query= MultiFieldQueryParser.parse(
"赵", new String[] {"name", "vocation"}, flags, new StandardAnalyzer());
hits = searcher.search(query);
printResult(hits, "名字或职业含有赵的结果",6);
}
/**
* 遍历索引[方式七:将索引结果排序]
* @throws Exception
*/
public void search_mod7()throws Exception{
Sort sort = new Sort(new SortField[]{new SortField("date", SortField.AUTO, true)});
RangeQuery query = null;
Hits hits = null;
Searcher searcher = new IndexSearcher(INDEX_DIR);
//当第二的参数为null时,后边界无限
query = new RangeQuery(new Term("date","1985-04-05"),
new Term("date","1988-05-02"), true);//true包括边界
hits = searcher.search(query,sort);
printResult(hits, "按时间大小",7);
}
public static void main(String[] args) {
SearchDb sdb = new SearchDb();
sdb.getResults();
sdb.indexDocs();
try {
sdb.search_mod1("all","0");//查询所有
System.out.println("------------------");
sdb.search_mod2("vocation","师");
System.out.println("------------------");
sdb.search_mod3("vocation","员");
System.out.println("------------------");
sdb.search_mod4();
System.out.println("------------------");
sdb.search_mod5();
System.out.println("------------------");
sdb.search_mod6();
System.out.println("------------------");
sdb.search_mod7();
} catch (CorruptIndexException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
分享到:
相关推荐
用lucene对数据库建立索引及搜索.doc
关于lucene对数据库建立索引和进行查询。这方面的东西太少了。大家应该多上传一些资料。
用Lucene.net对数据库建立索引及搜索
lucene建立数据库索引的问题,在这里,把其中的一些问题补充说明,希望对大家有新的帮助,希望大家相互提出问题,相互学习,共同进步!!
关于Lucene对数据操作,详细信息请见文档
Lucene(这里用到的是Lucene.net版本也成为DotLucene)是一个...本源码演示了Lucene结合Sql建立索引,把Sql中的数据通过建立索引用Lucene来检索 支持简单的中文分词,同时提供了Lucene.Net-2.0-004版本的源码给大家
对初学使用dotlucent作站...利用dotlucene为网站做的索引文件的应用程序。 数据库源是SQL Server,项目是用VS.NET2008开发的。 应用程序界面可以配置数据库链接,生成报告,定时执行增量索引,对单条索引进行更新操作。
lucene数据库索引.txt 新闻系统全文检索的思绪.txt lucene学习笔记 1 .txt lucene学习笔记 2.txt lucene学习笔记 3 .txt lucene入门实战.txt Lucene 的学习 .txt Lucene-2.0学习文档 .txt Lucene入门与使用...
这是用Lucene.NET结合Sql建立全文检索Demo的源码,适合初学者学习Lucene,其中包含所需的DLL文件。
第一章 Lucene是个倒排索引 第二章 Lucene与数据库 第三章 Lucene的索引建立及文件结构 第四章 Lucene的检索机制及文档得分 第五章 Lucene的存储优化 第六章 Lucene的效率优化 第七章 用Lucene加快web开发!
结构化数据和非结构化数据。 结构化数据:指具有固定格式或有限长度的数据,如数据库,元数据等。 非结构化数据:指不定长或无固定格式的数据,如邮件,word文档等
Lucene.Net,.net 的开源 全文搜索框架! 更多信息请查看 www.iubang.com
本文主要是利用Lucene对MS Sql Server 2000进行建立索引,然后进行全文索引。至于数据库的内容,可以是网页的内容,还是其它的。本文中数据库的内容是图书馆管理系统中的某个作者表- Authors表。
这是基于lucene搜索引擎的java源码,里面数据库,包括建立索引,增量索引一应俱全,希望对大家有作用。
你把数据扔给Lucene.Net,【Lucene.Net只针对文本信息建立索引,所以他只接收文本信息,如果不是文本信息,则要转换为文本信息】它会将文本内容分词后保存在索引库中,当用户输入关键字提交查询时,Lucene.Net从索引...
基于Lucene实现了一个海量数据库全文检索的原型。把关系数据库引入了本系统,可针对...采用多线程,通过动态机制来实现不同类型源数据库中记录的抽取、转换、建立索引;提供定时自动更新索引的功能;提供多种检索方式。
然后,利用 Lucene 的索引功能,将数据库中的公交信息建立索引,以便进行快速的搜索。 在搜索功能方面,可以实现基本的关键字搜索,用户可以通过输入线路号、站点名称等关键字来检索相关的公交信息。此外,还可以...
2. 全文搜索的两个工作: 建立索引文件,搜索索引. 3. Lucene的索引文件逻辑结构 1) 索引(Index)由若干块(片段)(Segment)组成 ★2) 块由若干文档(Document)组成: 一个文件映射成一个文档。数据库表中的一条记录...
它将其计划的索引更新(LuceneWork的)存储在数据库中,以供计划的作业稍后处理。 它设计用于单节点环境以及集群环境。 主要优点: 持久化到数据库后,计划的索引更新不会在节点崩溃的情况下丢失 无需在集群中...
lucene 基于lucene与IKAnalyzer的中文搜索demo及学习记录 Lucene是apache下的一个开放源代码的全文检索引擎工具包。...数据库:MySQL,建立名为lucene的数据库, () 项目框架:SpringBoot + lucene 6.6.5 + IK