添加jar包依赖
<dependency>
<groupId>org.apache.solr</groupId>
<artifactId>solr-solrj</artifactId>
<version>8.2.0</version>
</dependency>
添加spring java配置类 配置solr客户端
import org.apache.solr.client.solrj.impl.CloudSolrClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
/**
* @author ycw
* @date 2018年7月20日
*/
@Configuration
@PropertySource("classpath:config/solr.properties")
public class HttpSolrClient {
//solr collections的名称
@Value("${solr.index_core1}")
private String INDEXNAME_CORE1;
//zookeeper集群地址,有用几个就注册几个
@Value("${zk.host.url.12181}")
private String ZK_HOST_URL_12181;
@Value("${zk.host.url.12182}")
private String ZK_HOST_URL_12182;
@Value("${zk.host.url.12183}")
private String ZK_HOST_URL_12183;
public CloudSolrClient getCloudSolrClient() {
List<String> zkHosts = new ArrayList<String>();
//zookeeper集群地址,有用几个就注册几个
zkHosts.add(ZK_HOST_URL_12181);
// zkHosts.add(ZK_HOST_URL_12182);
// zkHosts.add(ZK_HOST_URL_12183);
//builder的构造函数需要一个List和一个Optional
Optional<String> zkChroot = Optional.of("/");
CloudSolrClient solrServer = new CloudSolrClient.Builder(zkHosts, zkChroot).build();
return solrServer;
}
//分词拆词 索引库
public CloudSolrClient getCore1SolrServer() {
CloudSolrClient cloudSolrClient = getCloudSolrClient();
cloudSolrClient.setDefaultCollection(INDEXNAME_CORE1);
return cloudSolrClient;
}
}
对solr数据进行操作
log.info("【导入临床指南索引库】导入临床指南数据。");
CloudSolrClient solrServer = null;
//初始化collections中的数据
//
try {
//查询数据库获取所有的用户
List<User> users= tzClinicalMapper.selectByExampleWithBLOBs(example);
//获取solr连接的collections
solrServer = httpSolrClient.getCore1SolrServer();
//循环遍历将所有的用户信息存入到solr中
for (User tzClinicalWithBLOBs : users) {
//创建solr输入文件
SolrInputDocument document = new SolrInputDocument();
//添加相应的值 类时json 对象 id:1
document.addField("id", tzClinicalWithBLOBs.getFieldid());
//类时的值 name:小王
document.addField("name",
tzClinicalWithBLOBs.getUseflag() == null ? 0 : tzClinicalWithBLOBs.getUseflag());
//将配置文件添加到solr服务中
solrServer.add(document);
//提交solr,类时于事务的原子性
solrServer.commit();
} catch (Exception e) {
throw new IndexException();
} finally {
//最后关闭solr服务
if (solrServer != null) {
try {
solrServer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
总体流程是先将zookeeper跟solr启动好,确保服务正常运行,接着在solrClound上面创建所需要的collections 配置好相应的分词
接着在代码上连接服务,设置连接到的服务片区(collection),才能进行数据的初始化或者搜索