SpringDataSolr的入门

36次阅读

共计 7039 个字符,预计需要花费 18 分钟才能阅读完成。

olr 和 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