在这篇文章中将通过代码带大家一步步实现spring和solrj的整合,并实现solrj的增删改查功能。

1.solrj的spring配置如下:

<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd"><!--value为solr项目的部署地址,在配置文件里面已经配置好,通过spring加载--><bean id="catalogHttpSolrClient" class="org.apache.solr.client.solrj.impl.HttpSolrClient"><constructor-arg index="0" value="${solrBaseUrl}catalog"/></bean></beans>

2.新建一个bean,属性名称要和solrcore的配置文件schema.xml的field一一对应,并用@field注解标识,否则实现不了solrj的增删改查。

package com.hover.bean;import org.apache.solr.client.solrj.beans.Field;public class CatalogBean {@Fieldprivate String catalogid;@Fieldprivate String catalogname;@Fieldprivate String fatherid;@Fieldprivate String photo;@Fieldprivate String iyear;@Fieldprivate String iway;@Fieldprivate String onsale;public String getIyear() {return iyear;}public void setIyear(String iyear) {this.iyear = iyear;}public String getIway() {return iway;}public void setIway(String iway) {this.iway = iway;}public String getOnsale() {return onsale;}public void setOnsale(String onsale) {this.onsale = onsale;}public String getCatalogid() {return catalogid;}public void setCatalogid(String catalogid) {this.catalogid = catalogid;}public String getCatalogname() {return catalogname;}public void setCatalogname(String catalogname) {this.catalogname = catalogname;}public String getFatherid() {return fatherid;}public void setFatherid(String fatherid) {this.fatherid = fatherid;}public String getPhoto() {return photo;}public void setPhoto(String photo) {this.photo = photo;}
}

3.下面是service类
(1)向solr插入一条数据有两种方式:新建一个SolrInputDocument和直接添加我们新建的bean。
(2)删除操纵要慎用,否则数据不可恢复。

package com.hover.service;import com.hover.bean.CatalogBean;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.common.params.FacetParams;
import org.springframework.stereotype.Service;import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;@Service
public class CataLogService {@Resource(name = "catalogHttpSolrClient")private SolrClient client;public void closeClient() throws Exception {client.commit();client.close();}public void addDoc(SolrInputDocument doc) throws Exception {client.add(doc);client.commit();client.close();}public void addBean(CatalogBean bean) throws Exception {client.addBean(bean);client.commit();client.close();}public void delete() throws Exception {//1.删除一个//updateResponse = client.deleteById("0");//2.删除多个
//        List<String> ids = new ArrayList<String>();
//        ids.add("10");
//        ids.add("11");
//        updateResponse = client.deleteById(ids);//3.根据查询条件删除数据,这里的条件只能有一个,不能以逗号相隔//updateResponse = client.deleteByQuery("fatherid:0");
//
//        //4.删除全部,删除不可恢复client.deleteByQuery("*:*");client.commit();client.close();}/*** 更新某一个属性的值* @param id* @param field* @param value* @throws Exception*/public void updateSet(int id, String field, String value) throws Exception {SolrInputDocument doc = new SolrInputDocument();HashMap<String, Object> operation = new HashMap<String, Object>();operation.put("set", value);doc.addField(field, operation);doc.addField("catalogid", id);client.add(doc);}/*** 数值型属性累加操作* @param id* @param field* @param value* @throws Exception*/public void updateInc(int id, String field, int value) throws Exception {SolrInputDocument doc = new SolrInputDocument();HashMap<String, Object> operation = new HashMap<String, Object>();operation.put("inc", value);doc.addField(field, operation);doc.addField("catalogid", id);client.add(doc);}/*** 多值属性附加一个值* @param id* @param field* @param value* @throws Exception*/public void updateAdd(int id, String field, String value) throws Exception {SolrInputDocument doc = new SolrInputDocument();HashMap<String, Object> operation = new HashMap<String, Object>();operation.put("add", value);doc.addField(field, operation);doc.addField("catalogid", id);client.add(doc);}/*** field多值属性附加多个值* @param id* @param field* @param list* @throws Exception*/public void updateMultiValueAdd(int id, String field, List<String> list) throws Exception {SolrInputDocument doc = new SolrInputDocument();Map<String,List<String>> photos=new HashMap<String, List<String>>();photos.put("add", list);doc.addField(field, photos);doc.addField("catalogid", id);client.add(doc);}/*** solr查询数据* @return* @throws Exception*/public QueryResponse query() throws Exception {SolrQuery query = new SolrQuery();//q 查询字符串,如果查询所有*:*query.set("q", "catalogid:*");//fq 过滤条件,过滤是基于查询结果中的过滤//query.set("fq", "catalogname:*驰*");//fq 此过滤条件可以同时搜索出奔驰和宝马两款车型,但是需要给catalogname配置相应的分词器//query.set("fq", "catalogname:奔驰宝马");//sort 排序,请注意,如果一个字段没有被索引,那么它是无法排序的query.set("sort", "catalogid desc");//start row 分页信息,与mysql的limit的两个参数一致效果query.setStart(0);query.setRows(100);//fl 指定返回那些字段内容,用逗号或空格分隔多个//query.set("fl", "catalogid,photo");return client.query(query);}/*** facet:solr多级分类功能* facet是solr的一个重要特性,可以一次实现根据多个字段的分类统计* @return* @throws Exception*/public QueryResponse facet() throws Exception {SolrQuery query = new SolrQuery();query.set("q", "*:*");//必须有查询条件,否则一下操作都是没有意义的,会出现null的情况//query.set("fq", "catalogname:*驰*");//过滤条件是建立在上述查询条件的基础之上的query.setFacet(true);//设置facet=true,默认为true//这里设置的开始index和行数是没有作用的//query.setStart(0);//query.setRows(10);query.addFacetField(new String[] {"iyear", "iway", "onsale"});//设置需要facet的字段query.setFacetLimit(5);//限制facet返回的数量//query.setFacetSort("index");//默认是按count来排序的query.setFacetSort(FacetParams.FACET_SORT_COUNT);return client.query(query);}}

4.下面是test类

import com.hover.bean.CatalogBean;
import com.hover.service.CataLogService;
import org.apache.solr.client.solrj.response.FacetField;
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.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import java.util.ArrayList;
import java.util.List;@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring/*.xml")
public class TestCataLogService {@AutowiredCataLogService cataLogService;@Testpublic void testAddDoc() throws Exception {SolrInputDocument doc = new SolrInputDocument();doc.addField("catalogid", 28);doc.addField("catalogname", "测试车型update");doc.addField("fatherid", 0);doc.addField("photo", "/img.jpg");doc.addField("iyear", "2017");doc.addField("iway", "ceshi");doc.addField("onsale", "1");cataLogService.addDoc(doc);}@Testpublic void testAddBean() throws Exception {CatalogBean bean = new CatalogBean();bean.setCatalogid("29");bean.setCatalogname("测试");bean.setFatherid("1");bean.setPhoto("/car.jpg");bean.setOnsale("1");bean.setIway("ceshi");bean.setIyear("2017");cataLogService.addBean(bean);}@Testpublic void testDelete() throws Exception {cataLogService.delete();}@Testpublic void testUpdate() throws Exception {cataLogService.updateSet(44, "catalogname", "测试");cataLogService.updateInc(44, "fatherid", 1);cataLogService.updateAdd(44, "photo", "/dasd.png");List<String> list = new ArrayList<String>();list.add("1.jpg");list.add("2.jpg");list.add("3.jpg");list.add("4.jpg");cataLogService.updateMultiValueAdd(44, "photo", list);cataLogService.closeClient();}@Testpublic void testQuery() throws Exception {QueryResponse queryResponse = cataLogService.query();SolrDocumentList results = queryResponse.getResults();System.out.println(results.toString());System.out.println("total:" + results.getNumFound());for (SolrDocument solrDocument: results) {System.out.println("-------" + solrDocument.get("catalogid") + "-------");System.out.println("车型id:" + solrDocument.get("catalogid"));System.out.println("车型名称:" + solrDocument.get("catalogname"));System.out.println("车型fatherId:" + solrDocument.get("fatherid"));System.out.println("车型照片:" + solrDocument.get("photo"));System.out.println();}}@Testpublic void testFacet() throws Exception {//调用service获取solrclient的查询结果QueryResponse queryResponse = cataLogService.facet();//获取查询的结果总数System.out.println("------total:" + queryResponse.getResults().getNumFound());//获取一级类ListList<FacetField> facetFieldList = queryResponse.getFacetFields();for (FacetField facetField: facetFieldList) {//输出一级类名称System.out.println("facetFeildName:" + facetField.getName() + "---count:" + facetField.getValues().size());List<FacetField.Count> countlist = facetField.getValues();for (FacetField.Count count: countlist) {//输出二级类名称和count值System.out.println(count.getName() + ":" + count.getCount());}System.out.println();}}}

源码下载地址为https://github.com/putTheoryIntoPractice/solrDemo.git

solr系列三:solr和spring整合并实现增删改查功能相关推荐

  1. 保姆级Spring+Mybatis整合的简单增删改查功能实现

    Springboot和Mybatis整合实现增删改查等 0.文章中pageHelper相关的操作是分页查询的东西与本文无关 1.首先创建一个Springboot的项目 1.1Java一般选择的是8,看 ...

  2. servlet增删改查实例_SpringBoot系列(2)整合MongoDB实现增删改查(完整案例)

    自己本科时候一直使用的是Mysql,目前的课题组使用的是MongoDB,因此就花了一部分时间整理了一下,实现springboot与MongoDB的整合,并且实现基本的增删改查操作,从头到尾给出一个完整 ...

  3. Ignite集群搭建及整合SpringData实现增删改查

    一.Ignite集群搭建 1.准备三个虚拟机.192.168.91.101.192.168.91.102.192.168.91.103 2.官网下载 Download - Apache Ignite ...

  4. Spring+SpringMVC+Mybatis实现增删改查--(五)SSM修改员工页面搭建

    Spring+SpringMVC+Mybatis实现增删改查--(五)SSM修改员工页面搭建 修改员工: 1.在index.jsp页面点击"编辑"弹出编辑对话框 2.去数据库查询部 ...

  5. Spring Boot (十五): Spring Boot + Jpa + Thymeleaf 增删改查示例

    <p>这篇文章介绍如何使用 Jpa 和 Thymeleaf 做一个增删改查的示例.</p> 先和大家聊聊我为什么喜欢写这种脚手架的项目,在我学习一门新技术的时候,总是想快速的搭 ...

  6. SSM整合--简单的增删改查--修改用户信息

    SSM整合--简单的增删改查 修改用户信息 修改用户信息 ## 根据id查找用户信息,显示在employ_update页面 ## 进行修改信息后,提交表单,保存数据### 1.根据id查询用户信息 h ...

  7. 3. mysql的注解驱动的三种方式_上手spring boot项目(三)之spring boot整合mybatis进行增删改查的三种方式。...

    1.引入依赖 org.springframework.boot spring-boot-starter-web org.mybatis.spring.boot mybatis-spring-boot- ...

  8. Spring Boot整合MongoDB实现增删改查

    MongoDB这两年来是本人一直使用较多的,之前的使用大多通过封装的工具类对数据库进行操作,虽然也算稳定,但有了Spring Boot之前的工具类直接加到SpringBoot里就没那么好使了,因此查阅 ...

  9. boot spring 接口接收数据_基于 Spring Boot 实现 Restful 风格接口,实现增删改查功能...

    优质文章,及时送达 Spring Boot介绍 Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程.该框架使用了特定的方式来进行配 ...

最新文章

  1. 百度js库tangram开源
  2. 福建2020年3月计算机二级报名时间,福建2020年3月计算机等级考试报名时间
  3. 为啥程序员工资高,却很多人想转行,这4点原很现实
  4. 二、python基础(列表、元组、字符串、集合、字典、文件操作,函数基本语法及特性)...
  5. Mysql主从复制,实现数据同步
  6. HTML5新特性-自定义属性(data-set)
  7. (转帖)对抽象编程:接口和抽象类
  8. Spring MVC BindingResult异常
  9. 计算机系统-CPU优化/特权级
  10. SpringBoot登录拦截器
  11. 全国计算机等级考试题photoshop,全国计算机等级考试之一级Photoshop试题
  12. 前端模拟数据(mock数据)的方法二:使用在线mock平台(fastmock)
  13. 联想万全服务器系列,联想服务器万全系列慧眼高级版操作快速入门
  14. Excel模板与Word模板【java】
  15. OCR中文简体汉字字符材料制作
  16. 康乐忆享|志愿者心得精选——张凌旭
  17. 阿里 + 京东 Java 岗面试题概要(面试须知)
  18. 地铁怎么坐才不能做反_[第一次]第一次一个人坐地铁,我坐反了方向
  19. Vue3通过npm或者yarn启动后,显示“Network: use --host to expose”,无法访问
  20. Matlab代码模板,图像处理,色彩补偿,色彩平衡,显示连通分量数量

热门文章

  1. 2021.11.13 关于大学生竞赛的些许感想,写在党课考试前一晚
  2. 3damx插件dle无法初始化 126找不到指定的模块
  3. 年金用计算机怎么算,cfa计算器计算年金
  4. 城市轨道交通运营管理专业就业前景怎么样?中职优选告诉你
  5. chrome DevTools 调试技巧
  6. 【技巧】让UI能跟随屏幕分辨率缩放
  7. Antd vue 和 element的表格高度根据浏览器高度变化
  8. 【Vue3系列】 父组件调用子组件的方法-子组件向父组件传值
  9. 软考高级-系统架构师-第五章软件架构设计
  10. 倍市得CEM-ISV合作共创:体验加持,共建数字化产品护城河