springboot集成solr详解
此项目使用的是分布式,当然案例可以新建一个springboot项目进行测试, solr服务器的搭建请参考
https://blog.csdn.net/ZHP131415/article/details/106027606
1.新建一个springboot项目,在项目中主要是作为一个搜索微服务
2.在搜索微服务learn_peace_search_service的配置文件中连接到solr服务器,文件类型为yml格式
spring:
data:
solr:
host: http://solr服务器地址:8080/solr
在pom.xml文件中添加依赖,当然它是一个web工程,必要的依赖还是需要有的:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-solr</artifactId>
<dependency>
3.在test中编写测试用例
package com.learn;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.io.IOException;
@SpringBootTest
@RunWith(SpringRunner.class)
public class LearnPeaceSearchServiceApplicationTestsTest {
@Autowired
private SolrClient solrClient;
/**
* 添加和修改是一个操作,就看唯一标识id是否可变
* 应用场景:用于数据的同步操作上,源头数据库发生变更,索引库也要跟着变更
* @throws IOException
* @throws SolrServerException
*/
@Test
public void addOrUpdateTest() throws IOException, SolrServerException {
//solr里面操作的记录,document
SolrInputDocument document = new SolrInputDocument();
//需要有唯一的标识
document.setField("id","11");
document.setField("product_name","thinkpad2019");
document.setField("product_price","9999");
document.setField("sale_point","速度快,现存非常棒,你值得拥有!!");
document.setField("product_images","无");
//提交
solrClient.add(document);
solrClient.commit();
}
@Test
public void queryData() throws IOException, SolrServerException {
//组装查询条件
SolrQuery queryCondition = new SolrQuery();
//查询所有
//queryCondition.setQuery("*:*");
//设置查询条件
queryCondition.setQuery("sale_point:速度很快"); //分词之后在匹配
//根据查询条件返回查询的结果集
QueryResponse response = solrClient.query(queryCondition);
SolrDocumentList results = response.getResults();
for (SolrDocument document : results) {
System.out.print(document.get("id"));
System.out.println(document.get("product_name"));
System.out.println(document.get("sale_point"));
}
}
@Test
public void deleteData() throws IOException, SolrServerException {
//精确匹配是按照id
//分词匹配
solrClient.deleteByQuery("sale_point:速度很快");
solrClient.commit();
}
}
添加和修改测试用例:
查询测试案例:
在这里主要是对sale_point的字段进行查找,且条件是queryCondition.setQuery("sale_point:速度很快"); //分词之后在匹配
查询结果:
10thinkpad2022
速度快,显卡牛
11thinkpad2019
速度快,现存非常棒,你值得拥有!!
删除测试案例:
后面继续更新!!!!!