最近在搞solr全文检索的功能,好一阵折腾,总结一下java操作solr服务器的用法。
第一步:引入Maven依赖。
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-solr</artifactId> </dependency>
第二步:配置solr基本参数,application.yml。
#solr全文检索配置 spring: application: name: solr data: solr: host: http://localhost:8080/solr/new_core/
第三步:编写SolrService,这里添加的数据要跟你在solr中配置映射的字段一样。
package com.allen.blog.service; import com.allen.blog.entity.ArticleSolr; 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.SolrDocumentList; import org.apache.solr.common.params.SolrParams; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; @Service public class SolrService { @Autowired private SolrClient solrClient; /** * solr查询全部内容 * @throws IOException * @throws SolrServerException */ public List<ArticleSolr> findSolrData() throws IOException, SolrServerException { SolrParams solrParams = new SolrQuery("*:*"); QueryResponse queryResponse = solrClient.query(solrParams); List<ArticleSolr> list = queryResponse.getBeans(ArticleSolr.class); return list; } /** * solr新增/修改 单条数据 * @param articleSolr * @throws IOException * @throws SolrServerException */ public void addSolrData(ArticleSolr articleSolr) throws IOException, SolrServerException { solrClient.addBean(articleSolr); solrClient.commit(); } /** * solr删除全部内容 * @throws IOException * @throws SolrServerException */ public void deleteSolrAll() throws IOException, SolrServerException { solrClient.deleteByQuery("*:*"); solrClient.commit(); } /** * solr删除单条数据 * @param id * @throws IOException * @throws SolrServerException */ public void deleteSolrById(String id) throws IOException, SolrServerException { solrClient.deleteById(id); solrClient.commit(); } }
SolrJ还有很多的接口,这里就不一一讲解了,详请参考API文档:http://lucene.apache.org/solr/8_2_0/solr-solrj/index.html