Spring Data Solr之快速入门
Spring Data Solr是为了方便Solr的开发所研制的一个框架,其底层是对SolrJ(官方API)的封装。
一、添加依赖
<dependencies>
<!--Spring-Data-Solr-->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-solr</artifactId>
<version>4.2.0.RELEASE</version>
</dependency>
<!--spring测试依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.2.9.RELEASE</version>
<scope>test</scope>
</dependency>
<!-- junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
</dependencies>
二、配置spring-solr.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:solr="http://www.springframework.org/schema/data/solr"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/data/solr
http://www.springframework.org/schema/data/solr/spring-solr.xsd">
<!--指定solr地址-->
<solr:solr-client id="solrClient" url="http://localhost:8080/solr"/>
<!-- solr模板,使用solr模板可对索引库进行CRUD的操作 -->
<bean id="solrTemplate" class="org.springframework.data.solr.core.SolrTemplate">
<constructor-arg ref="solrClient" />
</bean>
</beans>
三、配置User对象
创建User对象,同时属性使用@Field注解标识 ,@Field用于指定JavaBean中的属性和Solr索引库中对应的域的映射关系, 如果属性与配置文件定义的域名称不一致,需要在注解中指定域名称。
public class User {
@Field
private Long id;
@Field("user_name")
private String name;
@Field
private BigDecimal money;
@Field("user_address")
private String address;
@Field
private String phone;
@Field("user_eamail")
private String eamail;
}
四、managed-schema域配置
<field name="id" type="string" indexed="true" stored="true" required="true" multiValued="false" />
<field name="user_name" type="text_ik" indexed="true" stored="true"/>
<field name="money" type="string" indexed="true" stored="true"/>
<field name="user_address" type="text_ik" indexed="true" stored="true" />
<field name="phone" type="string" indexed="true" stored="true" />
<field name="user_eamail" type="string" indexed="true" stored="true" />
五、执行CRUD测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring-solr.xml")
public class SolrTest {
}
1.增加
new Bean
@Test
public void testAdd(){
User user = new User();
user.setId(1L);
user.setName("李白");
user.setMoney(new BigDecimal("100"));
user.setAddress("中国北京");
user.setPhone("6666");
user.setEamail("6666@qq.com");
//执行保存操作
UpdateResponse collection1 = solrTemplate.saveBean("collection1", user);
if ( collection1.getStatus()==0 ){
System.out.println("操作成功!");
}
//提交
solrTemplate.commit("collection1");
}
SolrInputDocument
@Test
public void testAdd(){
SolrInputDocument doc = new SolrInputDocument();
doc.setField("user_name","小黑");
doc.setField("user_address","中国上海");
doc.setField("phone","456987");
UpdateResponse collection1 = solrTemplate.saveBean("collection1", doc);
if ( collection1.getStatus()==0 ){
System.out.println("操作成功!");
}
//提交
solrTemplate.commit("collection1");
}
2.查询
1.按主键查询
@Test
public void testGetById(){
//查询id=1的数据
Optional<User> collection1 = solrTemplate.getById("collection1", 1L, User.class);
//User user = collection1.get();
//solrTemplate.getByIds("collection1", Arrays.asList(1,2,3,4), User.class);
System.out.println(collection1.orElse(null).getAddress());
}
2.分页查询
@Test
public void testPageSearch(){
Query query = new SimpleQuery("*:*");
//设置分页,开始索引(默认0)
query.setOffset(5L);
//每页记录数(默认10)
query.setRows(15);
//分页查询
ScoredPage<User> items = solrTemplate.queryForPage("collection1",query, User.class);
//总记录数
System.out.println("总记录数:"+items.getTotalElements());
for (User user : items.getContent()) {
System.out.println(user);
}
}
3.条件查询
@Test
public void testCondtionQuery(){
Query query = new SimpleQuery("*:*");
/***
* 封装查询条件
*
* Criteria("user_address"): 搜索user_address域对应的数据
*
* is("中国"): 搜索的数据包含中国关键词
*
*/
Criteria criteria = new Criteria("user_address").is("中国");
//把Criteria加入到Query中
query.addCriteria(criteria);
//设置分页,开始索引(默认0)
query.setOffset(0L);
//每页记录数(默认10)
query.setRows(10);
//分页查询
Page<User> collection1 = solrTemplate.query("collection1", query, User.class);
//总记录数
System.out.println("总记录数:"+collection1.getTotalElements());
//输出记录
for (User user : collection1.getContent()) {
System.out.println(user);
}
}
3.删除
1.按主键删除
@Test
public void testDeleteById(){
//删除id=1的数据
SimpleQuery simpleQuery = new SimpleQuery("id:1");
solrTemplate.delete("collection1", simpleQuery);
solrTemplate.commit("collection1");
}
- 删除全部数据
@Test
public void testDeleteAll(){
//"*:*":表示匹配所有数据的条件
Query query=new SimpleQuery("*:*");
solrTemplate.delete("collection1",query);
solrTemplate.commit("collection1");
}
4.排序
@Test
public void testSort(){
Query query = new SimpleQuery("*:*");
//设置分页,开始索引(默认0)
query.setOffset(5L);
//每页记录数(默认10)
query.setRows(15);
//排序
Sort sort = Sort.by(Sort.Direction.DESC, "id");
query.addSort(sort);
//分页查询
ScoredPage<User> items = solrTemplate.queryForPage("collection1",query, User.class);
//总记录数
System.out.println("总记录数:"+items.getTotalElements());
for (User user : items.getContent()) {
System.out.println(user);
}
}
5.高亮设置
@Test
public void testHighlightOptions(){
HighlightQuery query=new SimpleHighlightQuery(new SimpleStringCriteria("*:*"));
//按照关键字查询
Criteria criteria = new Criteria("user_name").is("小黑");
query.addCriteria(criteria);
query.setOffset(0L);
query.setRows(10);
//高亮设置
HighlightOptions highlightOptions = new HighlightOptions();
//设置高亮显示域
highlightOptions.addField("user_name");
//高亮前辍
highlightOptions.setSimplePrefix("<span style='color:red;'>");
//高亮后辍
highlightOptions.setSimplePostfix("</span>");
query.setHighlightOptions(highlightOptions);
HighlightPage<User> page = solrTemplate.queryForHighlightPage("collection1", query, User.class);
System.out.println("总记录数:"+page.getTotalElements());
for ( HighlightEntry<User> highlightEntry : page.getHighlighted()) {
//获取实体类
User user = highlightEntry.getEntity();
//获取高亮域列表
List<HighlightEntry.Highlight> highlights = highlightEntry.getHighlights();
for (HighlightEntry.Highlight highlight : highlights) {
//每个域有可能有多个值
List<String> snipplets = highlight.getSnipplets();
//高亮结果
System.out.println(snipplets!=null && highlights.get(0).getSnipplets().size()>0 ?snipplets.get(0) : "无高亮结果");
}
if(highlights!=null && highlights.size()>0 && highlights.get(0).getSnipplets()!=null && highlights.get(0).getSnipplets().size()>0){
String name = highlights.get(0).getSnipplets().get(0);
//替换高亮数据
user.setName(name);
}
}
}
6.添加动态域
managed-schema需配置动态域
<dynamicField name="user_test_*" type="string" indexed="true" stored="true" />
修改User,添加testDynamic字段。
@Dynamic
@Field("user_test_*")
private String testDynamic;
@Test
public void testDynamic(){
SolrInputDocument doc = new SolrInputDocument();
doc.setField("id",66);
doc.setField("user_name","小黑");
doc.setField("user_address","中国上海");
doc.setField("phone","456987");
doc.setField("user_test_Dynamic","动态域测试");
UpdateResponse collection1 = solrTemplate.saveBean("collection1", doc);
if ( collection1.getStatus()==0 ){
System.out.println("操作成功!");
}
//提交
solrTemplate.commit("collection1");
}
六、业务场景
假设:搜索关键字,同时搜索用户名字以及用户地址中含此关键字的数据,这里使用到复制域,需提前配置好。
配置域
一个简单、粗糙的业务完整域配置如下:
<field name="id" type="string" indexed="true" stored="true" required="true" multiValued="false" />
<field name="user_name" type="text_ik" indexed="true" stored="true"/>
<field name="money" type="string" indexed="true" stored="true"/>
<field name="user_address" type="text_ik" indexed="true" stored="true" />
<field name="phone" type="string" indexed="true" stored="true" />
<field name="user_eamail" type="string" indexed="true" stored="true" />
<dynamicField name="user_test_*" type="string" indexed="true" stored="true" />
<field name="user_keywords" type="text_ik" indexed="true" stored="false" multiValued="true"/>
<copyField source="user_address" dest="user_keywords"/>
<copyField source="user_name" dest="user_keywords"/>
业务实现
public class UserServiceImpl implements IUserService{
@Autowired
private SolrTemplate solrTemplate;
@Override
public HashMap<String,Object> searchData(String keyword) {
//创建Query对象,默认搜索所有数据,使用:*:*
Query query = new SimpleQuery("*:*");
if(StringUtils.isNotBlank(keyword)){
//使用到了定义的复制域user_keywords
Criteria criteria = new Criteria("user_keywords").is(keyword);
query.addCriteria(criteria);
}
//执行查询
ScoredPage<User> scoredPage = solrTemplate.queryForPage("collection1",query, User.class);
//获取集合数据
List<User> users = scoredPage.getContent();
//总记录数
long total = scoredPage.getTotalElements();
//定义返回对象
HashMap<String,Object> dataMap = new HashMap<>();
dataMap.put("rows",users);
dataMap.put("total",total);
return dataMap;
}
}
执行测试
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/137097.html