利用solrJ向索引库导入数据
需求:将MySQL中的数据导入到solr索引库
定义实体类:
- 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();
- this.id = id;
- this.title = title;
- this.sell_point = sell_point;
- this.price = price;
- this.image = image;
- this.category_name = category_name;
- }
- public SearchItem() {
- super();
- // 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, "导入失败!");
- }
- }