一.solr创建自定义field
如图所示,当程序从solr索引库进行搜索时,索引库需要先与数据库进行数据同步操作。因此,需要创建一些field属性字段与数据库表中的属性进行对应。
- 在linux中对solrcore的conf目录下的managed-schema文件进行配置:(1)
cd /usr/local/solrhome/solr_core1/conf
(2)vim managed-schema
加入如下业务域:
<!--配置商品信息的field -->
<!--业务域-->
<!--商品名称-->
<field name="name" type="text_ik" indexed="true" stored="true"/>
<!--商品价格-->
<field name="price" type="pint" indexed="true" stored="true" />
<!--商品卖点-->
<field name="sale_point" type="text_ik" indexed="true" stored="true" />
<!--商品图片-->
<field name="images" type="string" indexed="false" stored="true" />
<!--目标复制域-->
<field name="keywords" type="text_ik" indexed="true" stored="true" multiValued="true" />
<!--将商品添加到目标域-->
<copyField source="name" dest="keywords"/>
<copyField source="sale_point" dest="keywords"/>
其中,field中name标签是字段名(对应数据库表中选取的部分需要字段),type为字段类型,当type="text_ik"时表示使用ik中文分词器类型,indexed="true"表示一个field可以被搜索,stored="true"表示内容进行存储。
二.SpringBoot整合solr
- 创建maven工程时,Service层要选择solr依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-solr</artifactId>
</dependency>
- Service层在application.yml中配置solr服务器地址:
spring:
data:
solr:
host: http://192.168.157.129:8888/solr7/core1
这里tomcat8888端口号后面的solr7是指tomcat/webapps下所放的solr工程的名字,core1指的是solr页面中所指定的相应solrcore的名字。
- 在Test类中使用solr提供的客户端操作api:
@Autowired
private SolrClient solrClient;
- 单元测试,对索引库增删改查操作得示例:
@SpringBootTest
class QzlV9SearchServiceApplicationTests {
@Autowired
private SolrClient solrClient;
//增加与更新测试,根据id是否为新决定是增加还是更新操作
@Test
public void addOrUpdateTest() throws IOException, SolrServerException {
//solr里面的提交记录:以文档document的方式提交
SolrInputDocument document=new SolrInputDocument();
//需要一个唯一标识的id
document.setField("id","1");
document.setField("name","演唱会门票");
document.setField("price",1000);
document.setField("sale_point","好听");
document.setField("images","暂无");
//提交
solrClient.add(document);
solrClient.commit();
}
//查询测试
@Test
public void queryTest() throws IOException, SolrServerException {
//组装查询条件
SolrQuery solrQuery=new SolrQuery();
//在managed-schema中我们设置name的类型为text_ik,因此这里先进行分词再匹配
solrQuery.setQuery("name:张学友刘德华演唱会");
QueryResponse response=solrClient.query(solrQuery);
//
SolrDocumentList results=response.getResults();
for (SolrDocument document:results) {
System.out.println(document.get("id"));
System.out.println(document.get("name"));
System.out.println(document.get("price"));
System.out.println(document.get("sale_point"));
System.out.println(document.get("images"));
}
}
//删除测试
@Test
public void deleteTest() throws IOException, SolrServerException {
solrClient.deleteByQuery("name:演唱会");
solrClient.commit();
}
}
- 增加操作测试:
版权声明:本文为weixin_41570890原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。