`
xiuying
  • 浏览: 541697 次
  • 性别: Icon_minigender_1
  • 来自: 福建
社区版块
存档分类
最新评论

lucene 全文检索数据库

阅读更多

lucene 全文检索数据库
我们以前经常碰到搜索数据库的内容;用like %的sql语句;
如果数据量大而且多表查询时;
用lucene2那就可以解决速度问题。
lucene2搜索photo表的title,username,tagname,desr内容;
用一个例题来说明更直观;
此例题能搜索中文分词;
(需要mysql5的jdbc包和lucene2的包):
1、数据库我用mysql5;建一个photo表;数据库名是test。

photo表有一下几个字段:
CREATE TABLE `photo` (
`photo_id` int(11) NOT NULL auto_increment,
`title` varchar(11) default NULL,
`address` varchar(50) default NULL,
`descr` text,
`user_id` int(11) default NULL,
`user_name` varchar(11) default NULL,
`upload_time` date default NULL,
`tag_name` varchar(11) default NULL,
PRIMARY KEY (`photo_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=REDUNDANT;
2、java文件有4个:
文件Photo.java是数据库的photo表的操作文件;
内容如下:

import java.sql.Connection;
import java.util.ArrayList;
import java.util.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class Photo {
 private long photoId;
 private String title;
 private String description;
 private String address;
 private String userName;
 private long userId;
 private String tag;
 private Date date;

 public String getAddress() {
  return address;
 }

 public void setAddress(String address) {
  this.address = address;
 }

 public String getDescription() {
  return description;
 }

 public void setDescription(String description) {
  this.description = description;
 }

 public long getPhotoId() {
  return photoId;
 }

 public void setPhotoId(long photoId) {
  this.photoId = photoId;
 }

 public String getTag() {
  return tag;
 }

 public void setTag(String tag) {
  this.tag = tag;
 }

 public String getTitle() {
  return title;
 }

 public void setTitle(String title) {
  this.title = title;
 }

 public long getUserId() {
  return userId;
 }

 public void setUserId(long userId) {
  this.userId = userId;
 }

 public String getUserName() {
  return userName;
 }

 public void setUserName(String userName) {
  this.userName = userName;
 }

 public static Photo[] loadPhotos(Connection con) throws Exception {
  ArrayList<Photo> list = new ArrayList<Photo>();
  PreparedStatement pstm = null;
  ResultSet rs = null;
  String sql = "select photo_id,title,address,descr,user_id,user_name,upload_time,tag_name from photo";
  try {
   pstm = con.prepareStatement(sql);
   rs = pstm.executeQuery();
   while (rs.next()) {
    Photo photo = new Photo();
    photo.setPhotoId(rs.getLong(1));
    photo.setTitle(rs.getString(2));
    photo.setAddress(rs.getString(3));
    photo.setDescription(rs.getString(4));
    photo.setUserId(rs.getLong(5));
    photo.setUserName(rs.getString(6));
    photo.setDate(rs.getTimestamp(7));
    photo.setTag(rs.getString(8));
    
    list.add(photo);
   }
   System.out.println("com.upolestar.kmpm.po.Photo.java  ========"+list.size());
  } catch (SQLException e) {
   e.printStackTrace();
  } finally {
   if (rs != null) {
    rs.close();
   }
   if (pstm != null) {
    pstm.close();
   }
  }
  return (Photo[]) list.toArray(new Photo[list.size()]);
 }

 public Date getDate() {
  return date;
 }

 public void setDate(Date date) {
  this.date = date;
 }
}

文件IndexerFile.java是把数据库的内容备份成索引文件到磁盘中去;
内容如下:
package com.upolestar.kmpm.service;

import java.io.IOException;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexWriter;

import com.upolestar.kmpm.po.Photo;


public class IndexerFile {
 public static int indexFile(String indexDir, Photo[] list)
   throws IOException {
  IndexWriter writer = new IndexWriter(indexDir, new StandardAnalyzer(),
    true);
  writer.setUseCompoundFile(false);
  for (int i = 0; i < list.length; i++) {
   Document doc = new Document();
   doc.add(new Field("photoId", String.valueOf(list[i].getPhotoId()),
     Field.Store.YES, Field.Index.NO));
   if (list[i].getTitle() != null)
    doc.add(new Field("title", list[i].getTitle(), Field.Store.YES,
      Field.Index.TOKENIZED));
   if (list[i].getDescription() != null)
    doc.add(new Field("description", list[i].getDescription(),
      Field.Store.YES, Field.Index.TOKENIZED));
   doc.add(new Field("address", list[i].getAddress(), Field.Store.YES,
     Field.Index.NO));
   doc.add(new Field("userName", list[i].getUserName(),
     Field.Store.YES, Field.Index.TOKENIZED));
   doc.add(new Field("userId", String.valueOf(list[i].getUserId()),
     Field.Store.YES, Field.Index.NO));
   if (list[i].getTag().length() > 0)
    doc.add(new Field("tag", list[i].getTag(), Field.Store.YES,
      Field.Index.TOKENIZED));
   doc.add(new Field("uploadTime", list[i].getDate().toLocaleString(), Field.Store.YES,
     Field.Index.TOKENIZED));
   writer.addDocument(doc);
  }

  int numIndexed = writer.docCount();
  writer.optimize();
  writer.close();
  return numIndexed;
 }
}

文件SearcherFile.java是搜索磁盘索引文件内容的;
内容如下:
package com.upolestar.kmpm.service;

import java.io.IOException;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.queryParser.MultiFieldQueryParser;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.search.Hits;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.Searcher;

public class SearcherFile {
 public static void search(Searcher searcher, String[] q)
   throws IOException, ParseException {
  Analyzer analyzer = new StandardAnalyzer();
  String[] fields = { "title", "description", "tag", "userName" };
  Query query = MultiFieldQueryParser.parse(q, fields, analyzer);
  Hits hits = searcher.search(query);
  System.out.println("SearcherFile======"+hits.length());
  for (int i = 0; i < hits.length(); i++) {
   Document doc = hits.doc(i);
   System.out.println(doc.get("photoId") + "==="
     + doc.get("uploadTime")+ "==="
     + doc.get("title")+ "==="
     + doc.get("description")+ "==="
     + doc.get("tag")+ "==="
     + doc.get("userName"));
  }
 }
}

文件test.java是操作的主文件;
内容如下:
package com.upolestar.kmpm.test;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Date;

import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Searcher;

import com.upolestar.kmpm.po.Photo;
import com.upolestar.kmpm.service.IndexerFile;
import com.upolestar.kmpm.service.SearcherFile;

public class Test {
 public final static String indexDir = "D:\\TestLucene";

 private static Connection getConnection() {
  Connection conn = null;
  String url = "jdbc:mysql://localhost:3306/opencms";
  String userName = "root";
  String password = "1111";
  try {
   Class.forName("com.mysql.jdbc.Driver");
   conn = java.sql.DriverManager
     .getConnection(url, userName, password);
  } catch (Exception e) {
   e.printStackTrace();
   System.out.println("Error Trace in getConnection() : "
     + e.getMessage());
  }
  return conn;
 }

 public static void main(String[] args) throws IOException, ParseException,
   SQLException {
  index();// 做索引
  Searcher searcher = null;
  try {
   searcher = new IndexSearcher(indexDir);
   search(searcher);// 搜索
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   if (searcher != null)
    searcher.close();
  }
 }

 public static void search(Searcher searcher) throws IOException,
   ParseException {
  // 以下是搜索的关键词
  String[] q = { "SVN", "捱三", "null", "null" };
  long start = new Date().getTime();
  SearcherFile.search(searcher, q);
  long end = new Date().getTime();
  System.out.println("花费时间:" + (double) (end - start) / 1000 + "秒");
 }

 public static void index() throws SQLException {
  Connection conn = null;
  try {
   conn = getConnection();
   Photo[] list = Photo.loadPhotos(conn);
   IndexerFile.indexFile(indexDir, list);
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   if (conn != null) {
    conn.close();
   }
  }
 }
}

 

已经测试过!!

分享到:
评论

相关推荐

    使用lucene全文检索数据库

    **使用Lucene全文检索数据库** Lucene是一个高性能、全文本搜索库,由Apache软件基金会开发。它是Java编写的,能够帮助开发者在各种应用程序中实现强大的全文检索功能。在这个项目中,我们将探讨如何利用Lucene ...

    基于Lucene的Oracle数据库全文检索.pdf

    基于Lucene的Oracle数据库全文检索 基于Lucene的Oracle数据库全文检索是指使用Lucene搜索引擎来实现Oracle数据库中的全文检索。Lucene是一个开源的全文搜索引擎API,提供了完整的查询引擎和索引引擎,部分文本分析...

    一种基于Lucene检索引擎的全文数据库的研究与实现

    ### 一种基于Lucene检索引擎的全文数据库的研究与实现 #### 1. 引言 随着信息技术的飞速发展和互联网的普及,大量的文本信息被数字化存储,这为信息检索带来了前所未有的挑战和机遇。传统的数据库管理系统(DBMS)...

    lucene全文检索

    采用lucene全文检索技术,对文档进行全文检索,支持.java,.txt,.xml,.xls等文件的检索。采用mysql数据库。数据库并不包含在系统中,需要用户自己创建,数据库的配置在config/DB.properties文件中。能够检索出字符串...

    lucene全文检索简单索引和搜索实例

    《Lucene全文检索:简单索引与搜索实例详解》 Lucene是Apache软件基金会的开源项目,是一款强大的全文检索库,被广泛应用于Java开发中,为开发者提供了构建高性能搜索引擎的能力。在本文中,我们将深入探讨如何基于...

    Lucene全文检索案例

    **Lucene 全文检索案例** Lucene 是一个高性能、可扩展的信息检索库,由Apache软件基金会开发。它提供了一个简单但功能强大的API,用于在各种数据源中实现全文搜索。这个案例将深入探讨如何使用Lucene进行全文检索...

    SpringMvc+Lucene全文检索

    Lucene支持多种数据源,如文件、数据库等,可以快速地对大量文本数据进行检索。在我们的项目中,Lucene将用于抓取网页内容并建立索引,以便用户能快速找到相关的信息。 **3. 实现步骤** - **数据抓取**:使用Jsoup...

    用Lucene检索数据库

    【Lucene检索数据库详解】 Lucene是一个开源的全文搜索引擎库,它可以被集成到各种应用程序中,用于高效地创建、管理和搜索索引。在本场景中,我们探讨如何使用Lucene来检索数据库,尤其是针对MS SQL Server 2000的...

    Lucene与关系型数据库对比

    本文旨在深入探讨Lucene与关系型数据库之间的差异,尤其是它们在全文检索领域的表现,以期为企业和个人在选择合适的数据处理方案时提供参考。 ### Lucene:全文检索的革新者 Lucene由Doug Cutting创建,于2001年...

    Lucene检索数据库支持中文检索

    ### Lucene检索数据库支持中文检索 #### 一、Lucene简介与原理 ##### 1. Lucene概述 Lucene是一款高性能、全功能的文本搜索引擎库,由Java编写而成。其核心功能是为开发者提供构建搜索应用程序的基础框架。Lucene...

    用Lucene检索数据库.doc

    用Lucene检索数据库 Lucene是一种全文搜索的辅助工具,可以对数据库进行全文搜索,为我们带来了极大的便利和比较高的效率。本文主要是利用Lucene对MS Sql Server 2000进行建立索引,然后进行全文索引。下面将详细...

    Lucene全文检索框架+Solr搜索引擎(2018版.Java)

    **Lucene全文检索框架** Lucene是一个开源的Java全文检索库,由Apache软件基金会开发。它提供了文本分析、索引创建、文档检索等核心功能,是构建高效、可扩展搜索应用的基础。Lucene的主要特点包括: 1. **高速...

    lucene全文检索-javademo.rar

    lukeall.jar---双击,然后选择索引文件的位置,就可以看见里面的文件了! hello.java 是对文档的内容检索 ...TeacherIndex 是采用ssh框架的模式对数据库里面的表创建索引、添加增量索引、检索文件操作

    Lucene.Net 实现全文检索

    总的来说,Lucene.Net 在 .Net MVC4 上实现全文检索是一个涉及数据库交互、索引构建、查询处理和结果展示的综合过程。通过熟练掌握 Lucene.Net 的使用,可以为用户提供高效、准确的全文搜索体验。

    Lucene4 全文检索

    作为一个高级的搜索引擎工具包,Lucene4 提供了完整的索引和搜索机制,使得在文件和数据库中进行全文检索变得简单高效。在本文中,我们将深入探讨 Lucene4 的核心概念、工作流程以及如何在实际项目中应用。 ### 1. ...

Global site tag (gtag.js) - Google Analytics