利用solrJ向索引庫導入資料
需求:将MySQL中的資料導入到solr索引庫
定義實體類:
[java] view plain copy- public class SearchItem implements Serializable{
- private String id;
- private String title;
- private String sell_point;
- private long price;
- private String image;
- private String category_name;
- public String getId() {
- return id;
- }
- public void setId(String id) {
- this.id = id;
- 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 long getPrice() {
- return price;
- public void setPrice(long price) {
- this.price = price;
- public String getImage() {
- return image;
- public String[] getImages() {
- if(image != null && !"".equals(image)) {
- String[] images = image.split(",");
- return images;
- }
- return null;
- public void setImage(String image) {
- this.image = image;
- public String getCategory_name() {
- return category_name;
- public void setCategory_name(String category_name) {
- this.category_name = category_name;
- public SearchItem(String id, String title, String sell_point, long price, String image, String category_name) {
- super();
- public SearchItem() {
- // TODO Auto-generated constructor stub
- @Override
- public String toString() {
- return "SearchItem [id=" + id + ", title=" + title + ", sell_point=" + sell_point + ", price=" + price
- + ", image=" + image + ", category_name=" + category_name + "]";
定義mapper查詢資料庫:
- List<SearchItem> selectAllItem();
- <select id="selectAllItem" resultType="com.e3mall.search.SearchItem">
- SELECT
- a.id,
- a.title,
- a.sell_point,
- a.price,
- a.image,
- b.`name` category_name
- FROM
- tb_item a
- LEFT JOIN tb_item_cat b ON a.cid = b.id
- WHERE a.`status`=1
- </select>
- </mapper>
利用solrJ向索引庫導入資料:
- /**
- * 向索引庫添加資料
- */
- public E3Result saveSearch(){
- try {
- //從資料庫中查詢資料
- List<SearchItem> selectAllItem = searchMapper.selectAllItem();
- for (SearchItem searchItem : selectAllItem) {
- // 建立一個文檔對象SolrInputDocument
- SolrInputDocument document = new SolrInputDocument();
- // 向文檔對象中添加域,文檔中必須包含一個id域,所有的域的名稱必須在schema.xml中定義
- document.addField("id", searchItem.getId());
- document.addField("item_title", searchItem.getTitle());
- document.addField("item_sell_point", searchItem.getSell_point());
- document.addField("item_price", searchItem.getPrice());
- document.addField("item_image", searchItem.getImage());
- document.addField("item_category_name", searchItem.getCategory_name());
- // 把文檔寫入索引庫
- solrServer.add(document);
- // 送出
- solrServer.commit();
- //傳回成功
- return E3Result.ok();
- } catch (Exception e) {
- // TODO: handle exception
- return E3Result.build(500, "導入失敗!");
原文位址
http://www.bieryun.com/3229.html