A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

本帖最后由 阿莱 于 2019-7-25 09:55 编辑

【上海校区】SpringDataSolr的入门

Solr和SpringDataSolr的关系

solr 作为一个企业及应用,可以理解为一个搜索引擎的大体上的成品。solr的使用 是通过它提供的若干接口,而Spring Data Solr 是spring 调用solr接口的 进一步封装,简化了solr的使用,可以通过spring-data-solr提供的对象 HttpSolrServer 对文档索引的创建、搜索、分组、排序、分页等等进行操控。功能还是较为完善的。


准备工作和测试

第一步:配置solr服务的域

在你的solr服务所对应的本地库中,找到schema.xml的添加如下域

[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_updatetime" type="date" 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" />        


第二步:引入相关的依赖和JDK插件
[XML] 纯文本查看 复制代码
 <dependencies>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-solr</artifactId>
            <version>1.5.5.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>4.2.4.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.9</version>
        </dependency>

    </dependencies>

    <build>

        <plugins>
            <!-- java编译插件 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.7.0</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>

        </plugins>

    </build>

第三步:创建实体和编写属性相关的字段映射

自行提供setter和getter方法
[XML] 纯文本查看 复制代码
public class TbItem implements Serializable {

    @Field
    private Long id;

    @Field("item_title")
    private String title;

    @Field("item_price")
    private BigDecimal price;

    @Field("item_image")
    private String image;

    @Field("item_goodsid")
    private Long goodsId;

    @Field("item_category")
    private String category;

    @Field("item_brand")
    private String brand;

    @Field("item_seller")
    private String seller;

}


第四步:编写applicationContext-solr.xml
[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.pinyougou.solrutil">
    </context:component-scan>

    <!-- solr服务器地址 -->
    <solr:solr-server id="solrServer" url="http://127.0.0.1:8080/solr/collection1" />

    <!-- solr模板,使用solr模板可对索引库进行CRUD的操作 -->
    <bean id="solrTemplate" class="org.springframework.data.solr.core.SolrTemplate">

        <constructor-arg ref="solrServer" />

    </bean>
</beans>


第五步:进行Solr的集成测试
[Java] 纯文本查看 复制代码
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:applicationContext-solr.xml")
public class SpringDataSolrTest {

    @Autowired
    private SolrTemplate solrTemplate;

    //集成测试对应的单元
}


在对应的集成测试单元处编写测试方法

1、添加单个对象到solr
[Java] 纯文本查看 复制代码
    /**
     * 添加单个对象到solr
     */

    @Test
    public void beanAddSolr(){

        TbItem item=new TbItem();

        item.setId(1L);

        item.setBrand("华为");

        item.setCategory("手机");

        item.setGoodsId(1L);

        item.setSeller("华为2号专卖店");

        item.setTitle("华为Mate9");

        item.setPrice(new BigDecimal(2000));

        solrTemplate.saveBean(item);

        solrTemplate.commit();
    }


2、根据主键查询
[Java] 纯文本查看 复制代码
    /**
     * 根据主键查询
     */

    @Test
    public void findSolrById(){

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

        System.out.println(item.getTitle());
    }


3、根据主键删除
[Java] 纯文本查看 复制代码
  /**
     * 根据主键删除
     */

    @Test
    public void deleteSolrById(){

        UpdateResponse response = solrTemplate.deleteById("1");

        solrTemplate.commit();
    }


4、批量导入索引
[Java] 纯文本查看 复制代码
    /**
     * 将List集合中的对象添加到solr中
     */

    @Test
    public void beanListAddSolr(){

        List<TbItem> list=new ArrayList();

        for(int i=0;i<100;i++){

            TbItem item=new TbItem();

            item.setId(i+1L);

            item.setBrand("华为");

            item.setCategory("手机");

            item.setGoodsId(1L);

            item.setSeller("华为2号专卖店");

            item.setTitle("华为Mate"+i);

            item.setPrice(new BigDecimal(2000+i));

            list.add(item);
        }

        solrTemplate.saveBeans(list);

        solrTemplate.commit();
    }


5、分页查询

[Java] 纯文本查看 复制代码
    /**
     * 分页查询
     */

    @Test
    public void testPageQuery(){

        Query query=new SimpleQuery("*:*");

        //开始索引(默认0)
        query.setOffset(1);

        //每页记录数(默认10)
        query.setRows(20);

        ScoredPage<TbItem> page = solrTemplate.queryForPage(query, TbItem.class);

        System.out.println("总记录数:"+page.getTotalElements());

        List<TbItem> list = page.getContent();

        showList(list);
    }

    //显示记录数据
    private void showList(List<TbItem> list){

        for(TbItem item:list){

            System.out.println(item.getTitle() +item.getPrice());
        }
    }

    /**
     * 用于条件的封装
     */

    @Test
    public void testPageQueryMutil(){

        Query query=new SimpleQuery("*:*");

        Criteria criteria=new Criteria("item_title").contains("2");

        criteria=criteria.and("item_title").contains("5");

        query.addCriteria(criteria);

        //query.setOffset(20);//开始索引(默认0)
        //query.setRows(20);//每页记录数(默认10)
        ScoredPage<TbItem> page = solrTemplate.queryForPage(query, TbItem.class);

        System.out.println("总记录数:"+page.getTotalElements());

        List<TbItem> list = page.getContent();

        showList(list);
    }


6、高亮查询
[Java] 纯文本查看 复制代码
    @Test
    public void queryPageAndHightFromSolr(){

//        Query query=new SimpleQuery("item_title:手机");

        SimpleHighlightQuery query = new SimpleHighlightQuery();

        //开始索引(默认0)
        query.setOffset(1);

        //每页记录数(默认10)
        query.setRows(20);


        //设置高亮的域
        HighlightOptions highlightOptions = new HighlightOptions().addField("item_title").addField("item_category");


        //高亮前缀
        highlightOptions.setSimplePrefix("<em style='color:red'>");

        //高亮后缀
        highlightOptions.setSimplePostfix("</em>");

        //设置高亮选项
        query.setHighlightOptions(highlightOptions);


        //添加查询条件
        Criteria criteria = new Criteria("item_keywords").is("手机");

        query.addCriteria(criteria);

        HighlightPage<TbItem> items = solrTemplate.queryForHighlightPage(query, TbItem.class);

        List<HighlightEntry<TbItem>> highlighted = items.getHighlighted();

        for (HighlightEntry<TbItem> temHighlightEntry : highlighted) {

            List<HighlightEntry.Highlight> highlights = temHighlightEntry.getHighlights();


            TbItem item = temHighlightEntry.getEntity();

            for (HighlightEntry.Highlight highlight : highlights) {

                List<String> snipplets = highlight.getSnipplets();


                Field field = highlight.getField();

                String name = field.getName();

                for (String snipplet : snipplets) {

                    if ("item_title".equals(name)) {

                        item.setTitle(snipplet);
                    }

                    if ("item_category".equals(name)) {

                        item.setCategory(snipplet);
                    }
//                    System.out.println("snipplet = " + snipplet);
                }
            }


        }

       


        for (TbItem item : items) {

            System.out.println(item.getTitle());

            System.out.println("------------------------------");

            System.out.println(item.getCategory());
        }
        

    }


7、清空索引
[Java] 纯文本查看 复制代码
    /**
     * 删除solr全部数据
     */

    @Test
    public void deleteAllSolr(){

        Query query=new SimpleQuery("*:*");

        solrTemplate.delete(query);

        solrTemplate.commit();
    }







0 个回复

您需要登录后才可以回帖 登录 | 加入黑马