zoukankan      html  css  js  c++  java
  • Lucene4.8查询Mysql数据,写索引文件到本地——应用实例

    1.建立mysql数据库连接

    package cn.wqb.lucene;
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    
    public class JDBCUtils {
    
    	private static Connection conn = null;
    	private static final String url = "jdbc:mysql://localhost/project?autoReconnect=true&characterEncoding=utf8";
    	private static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
    	private static final String PASSWORD = "root";
    	private static final String USER_NAME = "root";
    	
    	public static Connection getConnection(){
    		try {
    			Class.forName(JDBC_DRIVER);
    			conn = DriverManager.getConnection(url,USER_NAME,PASSWORD);
    		} catch (ClassNotFoundException e) {
    			e.printStackTrace();
    		} catch (SQLException e) {
    			e.printStackTrace();
    		} 
    		return conn;
    	}
    }
    

    2.设计UI实体

    package cn.wqb.lucene;
    
    /**
     * 显示 实体Bean
     * @author qing
     *
     */
    public class ShowsBean {
    	private String id;
    	private String title;
    	private String sell_point;
    	private double price;
    	
    	public String getTitle() {
    		return title;
    	}
    
    	public void setTitle(String title) {
    		this.title = title;
    	}
    
    	public String getSell_point() {
    		return sell_point;
    	}
    
    	public void setSell_point(String sell_point) {
    		this.sell_point = sell_point;
    	}
    
    	public double getPrice() {
    		return price;
    	}
    
    	public void setPrice(double price) {
    		this.price = price;
    	}
    
    	public String getId() {
    		return id;
    	}
    
    	public void setId(String id) {
    		this.id = id;
    	}
    
    }
    

    3.建立 查询的常量

    package cn.wqb.lucene;
    
    public class SearchBean {
    	public static final String ID = "id";
    	public static final String TITLE = "title";
    	public static final String SELL_POINT = "sell_point";
    	public static final String PRICE = "price";
    }
    

    4.查询 及 写索引文件

    package cn.wqb.lucene;
    
    import java.io.File;
    import java.sql.Connection;
    import java.sql.ResultSet;
    import java.sql.Statement;
    import java.util.ArrayList;
    import java.util.List;
    
    import org.apache.lucene.analysis.Analyzer;
    import org.apache.lucene.document.Document;
    import org.apache.lucene.document.Field.Store;
    import org.apache.lucene.document.StringField;
    import org.apache.lucene.document.TextField;
    import org.apache.lucene.index.DirectoryReader;
    import org.apache.lucene.index.IndexReader;
    import org.apache.lucene.index.IndexWriter;
    import org.apache.lucene.index.IndexWriterConfig;
    import org.apache.lucene.index.Term;
    import org.apache.lucene.search.IndexSearcher;
    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.apache.lucene.util.Version;
    import org.wltea.analyzer.lucene.IKAnalyzer;
    
    public class TeamLogic {
    	private static Connection conn = null;
    	private static Statement stmt = null;
    	private static ResultSet rs = null;
    	private static File indexFile = null;
    	private static Directory directory = null;
    	private static Analyzer analyzer = null;
    	/** 索引页面缓冲 */
    	private int maxBufferedDocs = 500;
    	/** 指定索引文件存放地址  **/
    	private String searchDir = "c:/lucene/index03";
    
    	private static IndexSearcher indexSearcher = null;
    
    	/**
    	 * 获取数据库数据
    	 * 
    	 * @return ResultSet
    	 * @throws Exception
    	 */
    	public List<ShowsBean> getResult(String queryStr) throws Exception {
    		List<ShowsBean> result = null;
    		conn = JDBCUtils.getConnection();
    		if (conn == null) {
    			throw new Exception("数据库连接失败!");
    		}
    		String sql = "select id,title,sell_point,price from tb_item";
    		try {
    			stmt = conn.createStatement();
    			ResultSet rs = stmt.executeQuery(sql);
    			this.createIndex(rs); // 给数据库创建索引,此处执行一次,不要每次运行都创建索引,以后数据有更新可以后台调用更新索引
    			TopDocs topDocs = this.search(queryStr);
    			ScoreDoc[] scoreDocs = topDocs.scoreDocs;
    			result = this.addHits2List(scoreDocs);
    		} catch (Exception e) {
    			e.printStackTrace();
    			throw new Exception("数据库查询sql出错! sql : " + sql);
    		} finally {
    			if (rs != null)
    				rs.close();
    			if (stmt != null)
    				stmt.close();
    			if (conn != null)
    				conn.close();
    		}
    		return result;
    	}
    
    	/**
    	 * 为数据库检索数据创建索引
    	 * 
    	 * @param rs
    	 * @throws Exception
    	 */
    	private void createIndex(ResultSet rs) throws Exception {
    		IndexWriter indexWriter = null;
    
    		try {
    			// 根据给定的地址,查找文件
    			indexFile = new File(searchDir);
    			if (!indexFile.exists()) {
    				// 若文件不存在,则新建该文件
    				indexFile.mkdir();
    			}
    			
    			directory = FSDirectory.open(indexFile);// 文件写入磁盘
    			// 中文分词器
    			analyzer = new IKAnalyzer();
    			IndexWriterConfig conf = new IndexWriterConfig(Version.LUCENE_48,
    					analyzer);
    			indexWriter = new IndexWriter(directory, conf);
    			// 最大缓存文档数
    			conf.setMaxBufferedDocs(maxBufferedDocs);
    			// 将field写入document
    			Document doc = null;
    			while (rs.next()) {
    				doc = new Document();
    				StringField id = new StringField("id", 
    						rs.getString("id"),Store.YES);
    
    				StringField price = new StringField("price",
    						rs.getString("price"), Store.YES);
    
    				TextField title = new TextField("title",
    						rs.getString("title") == null ? "" 
    						: rs.getString("title"), Store.YES);
    
    				TextField sell_point = new TextField("sell_point",
    						rs.getString("sell_point") == null ? "" 
    						: rs.getString("sell_point"), Store.YES);
    
    				doc.add(id);
    				doc.add(title);
    				doc.add(price);
    				doc.add(sell_point);
    				// 将document写入文件
    				indexWriter.addDocument(doc);
    			}
    			// 关闭 一次写操作
    			indexWriter.close();
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    	}
    
    	/**
    	 * 搜索索引
    	 * 
    	 * @param queryStr
    	 * @return
    	 * @throws Exception
    	 */
    	private TopDocs search(String queryStr) throws Exception {
    		// int hitsPerPage = 10;
    		if (directory == null) {
    			directory = FSDirectory.open(indexFile);
    		}
    		IndexReader indexReader = DirectoryReader.open(directory);
    		// 创建搜索类
    		indexSearcher = new IndexSearcher(indexReader);
    		// 针对BeanField.TITLE进行的查询
    		// 搜索字段queryStr
    		Term term = new Term(SearchBean.TITLE, queryStr);
    		TermQuery termQuery = new TermQuery(term);
    		// 中文分词器
    		analyzer = new IKAnalyzer();
    		// 执行搜索
    		TopDocs topDocs = indexSearcher.search(termQuery, 1000);// 查询前多少条满足条件的数据
    		return topDocs;
    
    	}
    
    	/**
    	 * 返回结果并添加到List中
    	 * 
    	 * @param scoreDocs
    	 * @return
    	 * @throws Exception
    	 */
    	private List<ShowsBean> addHits2List(ScoreDoc[] scoreDocs)
    			throws Exception {
    		List<ShowsBean> listBean = new ArrayList<ShowsBean>();
    		ShowsBean bean = null;
    		for (int i = 0; i < scoreDocs.length; i++) {
    			int docId = scoreDocs[i].doc;
    			Document doc = indexSearcher.doc(docId);
    			bean = new ShowsBean();
    			bean.setId(doc.get("id"));
    			bean.setTitle(doc.get("title"));
    			bean.setPrice(Double.valueOf(doc.get("price")));
    			bean.setSell_point(doc.get("sell_point"));
    			listBean.add(bean);
    		}
    		return listBean;
    	}
    }
    

    5.业务调配

    package cn.wqb.lucene;
    
    import java.util.List;
    
    public class IndexForMysql {
    
    	// 建立与mysql的连接
    	public void useSearchLogin() {
    		TeamLogic logic = new TeamLogic();
    		try {
    			Long startTime = System.currentTimeMillis();
    			List<ShowsBean> result = logic.getResult("小米");
    			int i = 0;
    			for (ShowsBean bean : result) {
    				if (i == 10)
    					break;
    				System.out.println("bean.name :" + bean.getClass().getName()
    						+ " bean.id: " + bean.getId() + " bean.getTitle: "
    						+ bean.getTitle() + " bean.getSell_point: "
    						+ bean.getSell_point() + " bean.getPrice :"
    						+ bean.getPrice());
    				i++;
    			}
    
    			System.out.println("searchBean.result.size : " + result.size());
    			Long endTime = System.currentTimeMillis();
    			System.out.println("查询所花费的时间为:" + (endTime - startTime) / 1000);
    		} catch (Exception e) {
    			e.printStackTrace();
    			System.out.println(e.getMessage());
    		}
    
    	}
    }
    

    6.执行测试

    package cn.wqb.lucene;
    
    import org.junit.Test;
    
    public class TestLuceneForMysql {
    	
    	@Test
    	public void testSearchLogic(){
    		IndexForMysql instance = new IndexForMysql();
    		instance.useSearchLogin();
    	}
    	
    }
    
  • 相关阅读:
    python-异常处理总结
    python-笔记-内置函数
    python练习题--计算总分平均分操作excel
    python-笔记(操作excel)
    python -加密(MD5)
    jmeter-http信息头管理器
    python-判断一个字符串是不是小数
    [Python] [Django] Django将post请求变成get
    离线安装rabbitmq
    python第三方包的几种安装方式
  • 原文地址:https://www.cnblogs.com/bridgestone29-08/p/6486187.html
Copyright © 2011-2022 走看看