Java项目实战 - solr导入索引库

实现:
使用java程序读取mysql数据库中的商品信息,然后创建solr文档对象,把商品信息写入索引库。

Dao

多表查询,要创建相应的POJO和Mapper。
POJO:

1
2
3
4
5
6
7
8
9
public class Item {
private String id;
private String title;
private String sell_point;
private long price;
private String image;
private String category_name;
private String item_des;
}

Mapper:

1
2
3
public interface ItemMapper {
List<Item> getItemList();
}

  • xml
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
    <mapper namespace="com.izheyi.search.mapper.ItemMapper" >

    <select id="getItemList" resultType="com.izheyi.search.pojo.Item">
    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
    </select>
    </mapper>

Service

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
@Service
public class ItemServiceImpl implements ItemService {

@Autowired
private ItemMapper itemMapper;

@Autowired
private SolrServer solrServer;

@Override
public TaotaoResult importItemsToSolr() {
try {

//查询商品列表
List<Item> list = itemMapper.getItemList();
//把商品信息写入索引库
for (Item item : list) {
//创建一个SolrInputDocument对象
SolrInputDocument document = new SolrInputDocument();
document.setField("id", item.getId());
document.setField("item_title", item.getTitle());
document.setField("item_sell_point", item.getSell_point());
document.setField("item_price", item.getPrice());
document.setField("item_image", item.getImage());
document.setField("item_category_name", item.getCategory_name());
document.setField("item_desc", item.getItem_des());
//写入索引库
solrServer.add(document);
}
//提交修改
solrServer.commit();
} catch (Exception e) {
e.printStackTrace();
return TaotaoResult.build(500, ExceptionUtil.getStackTrace(e));
}
return TaotaoResult.ok();
}
}

需要配置applicationContext-solr.xml。

Controller

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Controller
@RequestMapping("/manager")
public class ItemController {

@Autowired ItemService itemService;

@RequestMapping("/import")
@ResponseBody
public TaotaoResult importItemsToSolr(){
TaotaoResult result = itemService.importItemsToSolr();

return result;
}

}

唐胡璐 wechat
欢迎您扫一扫上面的微信公众号,订阅我的博客!
分享创造价值,您的支持将鼓励我继续前行!