1. 程式人生 > >spring-data-solr

spring-data-solr

odin query contex ued 總頁數 eat void cost usr

  Spring Data Solr就是為了方便Solr的開發所研制的一個框架,其底層是對SolrJ(官方API)的封裝

(1) 配置業務域

  vim /usr/local/solr/solrhome/collection1/conf/schema.xml

<field name="item_goodsid" type="long" indexed="true" stored="true"/>
<field name="item_title" type="text_ik" indexed="true" stored="true"/>
<field name="item_price" type="double" indexed="true" stored="true"/>
<field name="item_image" type="string" indexed="false" stored="true" />
<field name="item_category" type="string" indexed="true" stored="true" />
<field name="item_seller" type="text_ik" indexed="true" stored="true" />
<field name="item_brand" type="string" indexed="true" stored="true" />
<field name="item_keywords" type="text_ik" indexed="true" stored="false" multiValued="true"/>
<!-- 復制域 -->
<copyField source="item_title" dest="item_keywords"/> <copyField source="item_category" dest="item_keywords"/> <copyField source="item_seller" dest="item_keywords"/> <copyField source="item_brand" dest="item_keywords"/> <!-- 動態域 --> <dynamicField name="item_spec_*" type="string" indexed="true" stored="true" />

(2) 引入相關依賴

<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-solr</artifactId>
    <version>1.5.5.RELEASE</version>
</dependency>

(3) 在相應pojo類中添加@Field註解

public class TbItem implements Serializable{
    private
static final long serialVersionUID = 1L; @Field private Long id; @Field("item_title") private String title; private String sellPoint; @Field("item_price") private BigDecimal price; private Integer stockCount; private Integer num; private String barcode; @Field(
"item_image") private String image; private Long categoryid; private String status; private Date createTime; @Field("item_updatetime") private Date updateTime; private String itemSn; private BigDecimal costPirce; private BigDecimal marketPrice; private String isDefault; @Field("item_goodsid") private Long goodsId; private String sellerId; private String cartThumbnail; @Field("item_category") private String category; @Field("item_brand") private String brand; private String spec; @Field("item_seller") private String seller; @Dynamic @Field("item_spec_*") private Map<String,String> specMap;

(4) xml配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:solr="http://www.springframework.org/schema/data/solr"
    xsi:schemaLocation="http://www.springframework.org/schema/data/solr 
          http://www.springframework.org/schema/data/solr/spring-solr-1.0.xsd
        http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context.xsd">
  <context:component-scan base-package="com.xxx.solrUtil"></context:component-scan> <!-- solr服務器地址 --> <solr:solr-server id="solrServer" url="http://127.0.0.1:8081/solr" /> <!-- solr模板,使用solr模板可對索引庫進行CRUD的操作 --> <bean id="solrTemplate" class="org.springframework.data.solr.core.SolrTemplate"> <constructor-arg ref="solrServer" /> </bean> </beans>

(5) 導入數據代碼

@Component
public class SolrUtil {
    
    @Autowired
    private TbItemMapper itemMapper;
    
    @Autowired
    private SolrTemplate solrTemplate;
    
    public void importItemData(){
        TbItemExample example = new TbItemExample();
        Criteria criteria = example.createCriteria();
        criteria.andStatusEqualTo("1");
        
        List<TbItem> list = itemMapper.selectByExample(example);
        
        System.out.println("---商品列表---");
        
        for (TbItem tbItem : list) {
            System.out.println(tbItem.getId()+" "+ tbItem.getTitle()+ " "+tbItem.getPrice());
            // 動態域數據
            String spec = tbItem.getSpec();
            // FastJSON的泛型
            Map<String, String> map = JSON.parseObject(spec, new TypeReference<Map<String, String>>(){});
            tbItem.setSpecMap(map);
        }
        
        solrTemplate.saveBeans(list);
        solrTemplate.commit();
        
        System.out.println("---結束---");
        
    }
}

(6) 高亮顯示

    // TODO 搜索關鍵字列表(關鍵字高亮)
    private Map<String, Object> searchList(Map<String, Object> searchMap) {
    // ************************ 關鍵字 ************************
   // 設置關鍵字搜索域(可以設置多個搜索域)
   Criteria criteria = new Criteria("item_keywords");
   criteria.is(searchMap.get("keywords"));
   query.addCriteria(criteria);
    // ************************ 條件過濾 ************************
    FilterQuery filterQuery = new SimpleFilterQuery();
    Criteria filterCriteria = new Criteria("item_title");
   filterCriteria.is(searchMap.get(key));
   filterQuery.addCriteria(filterCriteria);
   query.addFilterQuery(filterQuery);
    
// ************************ 高亮初始化 ************************ // 創建搜索對象(普通搜索) // Query query = new SimpleQuery("*:*"); // 創建搜索對象(高亮搜索) SimpleHighlightQuery query = new SimpleHighlightQuery(); // 設置高亮選項對象 HighlightOptions highlightOptions = new HighlightOptions(); highlightOptions.addField("item_title");// 設置高亮域 highlightOptions.setSimplePrefix("<span style=‘color: red;‘>");// 設置高亮前綴 highlightOptions.setSimplePostfix("</span>");// 設置高亮後綴 // 設置高亮選項 query.setHighlightOptions(highlightOptions);// 普通搜索 // ScoredPage<TbItem> page = solrTemplate.queryForPage(query, TbItem.class); // ************************ 獲取高亮 ************************ // 所搜結果 HighlightPage<TbItem> page = solrTemplate.queryForHighlightPage(query, TbItem.class); List<HighlightEntry<TbItem>> highlightedResult = page.getHighlighted();// 高亮結果集 for (HighlightEntry<TbItem> entry : highlightedResult) { List<Highlight> highlightList = entry.getHighlights(); // 只設定一個搜索域,entry.getHighlights()只有1個值,highlightList.get(0).getSnipplets()也只有1個值 if (highlightList.size() > 0 && highlightList.get(0).getSnipplets().size() > 0) { // 設置高亮 TbItem tbItem = entry.getEntity(); tbItem.setTitle(highlightList.get(0).getSnipplets().get(0)); // System.out.println(tbItem.getId() + " " + tbItem.getTitle() + " " + tbItem.getPrice()); } } map.put("rows", page.getContent());// 搜索結果 map.put("totalPages", page.getTotalPages());// 總頁數 map.put("total", page.getTotalElements());// 總記錄數 System.out.println("rows: " + page.getContent() + ",totalPages: " + page.getTotalPages() + ",total: " + page.getTotalElements()); return map; }

(7) solrTemplate常用方法

  1) 添加/修改

solrTemplate.saveBean(item);

  2) 主鍵查詢

Item item = solrTemplate.getById(1, Item.class);

  3) 主鍵刪除

solrTemplate.deleteById("1");

  4) 分頁

Query query=new SimpleQuery("*:*");
query.setOffset(20);//開始索引(默認0)
query.setRows(20);//每頁記錄數(默認10)
ScoredPage<Item> page = solrTemplate.queryForPage(query, Item.class);
List<Item> list = page.getContent();

  5) 條件查詢

Query query=new SimpleQuery("*:*");
Criteria criteria=new Criteria("item_title").contains("2");
criteria=criteria.and("item_title").contains("5");        
query.addCriteria(criteria);
ScoredPage<Item> page = solrTemplate.queryForPage(query, Item.class);
List<TbItem> list = page.getContent();

  6) 刪除所有

Query query=new SimpleQuery("*:*");
solrTemplate.delete(query);

  7) 提交(cud)

solrTemplate.commit();

  8) 關於動態域搜索

item_spec_網絡;item_spec_機身內存
spec = {‘key1‘:‘value1‘, ‘key2‘:‘value2‘};spec = {‘網絡‘:‘value1‘, ‘機身內存‘:‘value2‘} Map<String, String> spec = (Map<String, String>) searchMap.get("spec"); for (String key : spec.keySet()) { String value = spec.get(key); FilterQuery filterQuery = new SimpleFilterQuery(); Criteria filterCriteria = new Criteria("item_spec_" + key); filterCriteria.is(value); filterQuery.addCriteria(filterCriteria); query.addFilterQuery(filterQuery); }

spring-data-solr