当前位置:   article > 正文

从零开始:SpringBoot整合ElasticSearch实现简单增删改查_springboot elasticsearch 增

springboot elasticsearch 增

        新建springboot项目就不再赘述,相关教程非常多,很容查到。Elasticsearch在windows与linux环境下的安装与使用可以参考以下文章:

Linux/windows环境下后端基础服务(tomcat,MongoDB, docker, elasticsearch等)部署说明

Elasticsearch+Postman简单入门

Springboot集成ElasticSearch

1.引入相关依赖

        es版本以自己安装的版本为准

  1. <dependency>
  2. <groupId>com.alibaba</groupId>
  3. <artifactId>fastjson</artifactId>
  4. <version>1.2.41</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.elasticsearch.client</groupId>
  8. <artifactId>elasticsearch-rest-high-level-client</artifactId>
  9. <version>7.13.2</version>
  10. </dependency>

2.在application.properties文件中配置es连接

        可同时配置多个es连接

  1. server.port=9650
  2. spring.servlet.multipart.enabled=false
  3. spring.servlet.multipart.file-size-threshold=0
  4. spring.servlet.multipart.max-file-size=1MB
  5. spring.servlet.multipart.max-request-size=10MB
  6. elasticsearch.http.host=localhost
  7. elasticsearch.http.port=9200
  8. elasticsearch.user.index=user
  9. elasticsearch.user.type=userInfo

3.编写配置类

  1. package com.example.elasticsearchdemo.config;
  2. import org.apache.http.HttpHost;
  3. import org.elasticsearch.client.RestClient;
  4. import org.elasticsearch.client.RestClientBuilder;
  5. import org.elasticsearch.client.RestHighLevelClient;
  6. import org.springframework.beans.factory.annotation.Value;
  7. import org.springframework.context.annotation.Bean;
  8. import org.springframework.context.annotation.Configuration;
  9. @Configuration
  10. public class ElasticsearchConfig {
  11. @Value("${elasticsearch.http.host}")
  12. private String esHost;
  13. @Value("${elasticsearch.http.port}")
  14. private int esPort;
  15. @Bean
  16. public RestHighLevelClient esRestClient() {
  17. RestClientBuilder builder = null;
  18. builder = RestClient.builder(new HttpHost(esHost,esPort,"http"));
  19. RestHighLevelClient restHighLevelClient = new RestHighLevelClient(builder);
  20. return restHighLevelClient;
  21. }
  22. }

编写简单增删改查示例

1.用 postman 在es中设计并新建索引和映射

        具体方法可参考文章:

        Elasticsearch+Postman简单入门

        映射如下:

  1. {
  2. "mappings": {
  3. "userInfo": {
  4. "properties": {
  5. "id": {
  6. "type": "text",
  7. "fields": {
  8. "keyword": {
  9. "type":"keyword",
  10. "ignore_above":256
  11. }
  12. }
  13. },
  14. "name": {
  15. "type": "text",
  16. "fields": {
  17. "keyword": {
  18. "type":"keyword",
  19. "ignore_above":256
  20. }
  21. }
  22. },
  23. "age": {
  24. "type": "integer",
  25. "fields": {
  26. "keyword": {
  27. "type":"keyword",
  28. "ignore_above":256
  29. }
  30. }
  31. },
  32. "sex": {
  33. "type": "text",
  34. "fields": {
  35. "keyword": {
  36. "type":"keyword",
  37. "ignore_above":256
  38. }
  39. }
  40. },
  41. "interest ": {
  42. "type": "text",
  43. "fielddata": true,
  44. "fields": {
  45. "keyword": {
  46. "type":"keyword",
  47. "ignore_above":256
  48. }
  49. }
  50. }
  51. }
  52. }
  53. }
  54. }

2.在springboot中新建user类

        参考es映射新建对应的user类

  1. ackage com.example.elasticsearchdemo.bean;
  2. import org.springframework.data.annotation.Id;
  3. public class User {
  4. @Id
  5. private String id;
  6. private String name;
  7. private Integer age;
  8. private String sex;
  9. private String interest;
  10. public String getId() {
  11. return id;
  12. }
  13. public void setId(String id) {
  14. this.id = id;
  15. }
  16. public String getName() {
  17. return name;
  18. }
  19. public void setName(String name) {
  20. this.name = name;
  21. }
  22. public Integer getAge() {
  23. return age;
  24. }
  25. public void setAge(Integer age) {
  26. this.age = age;
  27. }
  28. public String getSex() {
  29. return sex;
  30. }
  31. public void setSex(String sex) {
  32. this.sex = sex;
  33. }
  34. public String getInterest() {
  35. return interest;
  36. }
  37. public void setInterest(String interest) {
  38. this.interest = interest;
  39. }
  40. @Override
  41. public String toString() {
  42. return "User{" +
  43. "id='" + id + '\'' +
  44. ", name='" + name + '\'' +
  45. ", age=" + age +
  46. ", sex='" + sex + '\'' +
  47. ", interest='" + interest + '\'' +
  48. '}';
  49. }
  50. }

3.实现简单增删改查

        注:若传入参数user对象包含id且es中已存在相同id,则更新替换;否则新建用户。条件查询中若传入map为空,则返回所有;否则执行多条件查询操作。

1)Controller层

  1. package com.example.elasticsearchdemo.controller;
  2. import com.alibaba.fastjson.JSONObject;
  3. import com.example.elasticsearchdemo.bean.User;
  4. import com.example.elasticsearchdemo.service.UserService;
  5. import org.springframework.web.bind.annotation.*;
  6. import javax.annotation.Resource;
  7. import java.util.ArrayList;
  8. import java.util.List;
  9. import java.util.Map;
  10. @RestController
  11. @RequestMapping("/user")
  12. @CrossOrigin(value = "*", maxAge = 3600)
  13. public class UserController {
  14. @Resource
  15. private UserService service;
  16. /**新增与修改用户*/
  17. @RequestMapping(value = "save", method = RequestMethod.POST)
  18. public JSONObject saveUser(@RequestBody User user) {
  19. JSONObject output = new JSONObject();
  20. Map<String, Object> result = service.saveUser(user);
  21. output.put("msg", result);
  22. return output;
  23. }
  24. /**删除用户*/
  25. @RequestMapping(value = "delete/{id}", method = RequestMethod.DELETE)
  26. public JSONObject deleteUser(@PathVariable("id") String id) {
  27. JSONObject output = new JSONObject();
  28. Map<String, Object> result = service.deleteUser(id);
  29. output.put("msg", result);
  30. return output;
  31. }
  32. /**条件查询*/
  33. @RequestMapping(value = "get", method = RequestMethod.POST)
  34. public JSONObject getUsers(@RequestBody Map<String,Object> maps) throws Exception{
  35. JSONObject output = new JSONObject();
  36. List result = new ArrayList();
  37. if (maps != null) {
  38. result = service.getUsers(maps);
  39. } else {
  40. result = service.getAllUsers();
  41. }
  42. output.put("data", result);
  43. return output;
  44. }
  45. }

2)Service层

  1. package com.example.elasticsearchdemo.service;
  2. import com.example.elasticsearchdemo.bean.User;
  3. import com.example.elasticsearchdemo.dao.common.UserEsDao;
  4. import org.springframework.stereotype.Service;
  5. import javax.annotation.Resource;
  6. import java.util.List;
  7. import java.util.Map;
  8. import java.util.UUID;
  9. @Service
  10. public class UserService {
  11. @Resource
  12. private UserEsDao userEsDao;
  13. /**如果存在用户就修改,不存在就新增*/
  14. public Map<String, Object> saveUser(User user) {
  15. if (user.getId() == null) {
  16. //生成唯一随机id
  17. String id = UUID.randomUUID().toString().substring(24);
  18. user.setId(id);
  19. }
  20. return userEsDao.saveUser(user);
  21. }
  22. public Map<String,Object> deleteUser(String id) {
  23. return userEsDao.deleteUser(id);
  24. }
  25. public List getAllUsers() throws Exception{
  26. return userEsDao.getUsers(null);
  27. }
  28. public List getUsers(Map<String,Object> maps) throws Exception{
  29. return userEsDao.getUsers(maps);
  30. }
  31. }

3)Dao层

  1. package com.example.elasticsearchdemo.dao.common;
  2. import com.alibaba.fastjson.JSON;
  3. import com.alibaba.fastjson.JSONObject;
  4. import com.example.elasticsearchdemo.bean.User;
  5. import com.fasterxml.jackson.core.JsonProcessingException;
  6. import com.fasterxml.jackson.databind.ObjectMapper;
  7. import org.elasticsearch.action.bulk.BulkRequest;
  8. import org.elasticsearch.action.bulk.BulkResponse;
  9. import org.elasticsearch.action.delete.DeleteRequest;
  10. import org.elasticsearch.action.index.IndexRequest;
  11. import org.elasticsearch.action.search.SearchRequest;
  12. import org.elasticsearch.action.search.SearchResponse;
  13. import org.elasticsearch.client.RequestOptions;
  14. import org.elasticsearch.client.RestHighLevelClient;
  15. import org.elasticsearch.index.query.*;
  16. import org.elasticsearch.search.SearchHit;
  17. import org.elasticsearch.search.builder.SearchSourceBuilder;
  18. import org.elasticsearch.search.sort.SortOrder;
  19. import org.springframework.beans.factory.annotation.Autowired;
  20. import org.springframework.beans.factory.annotation.Value;
  21. import org.springframework.stereotype.Repository;
  22. import java.io.IOException;
  23. import java.util.*;
  24. @Repository
  25. public class UserEsDao {
  26. @Autowired
  27. private RestHighLevelClient client;
  28. @Value("${elasticsearch.user.index}")
  29. private String userIndex;
  30. @Value("${elasticsearch.user.type}")
  31. private String userType;
  32. /**
  33. * 往es中插入新数据
  34. */
  35. public Map<String, Object> saveUser(User user){
  36. Map<String,Object> ret = new HashMap<>();
  37. Map map = null;
  38. try{
  39. //实体转换成map以请求es
  40. map = JSON.parseObject(JSON.toJSONString(user), Map.class);
  41. }catch (Exception e){
  42. e.printStackTrace();
  43. }
  44. BulkRequest bulkRequest = new BulkRequest();
  45. //IndexRequest构造函数第三个参数指定id
  46. bulkRequest.add(new IndexRequest(userIndex,userType,user.getId()).source(map));
  47. try{
  48. BulkResponse bulkResponse = client.bulk(bulkRequest, RequestOptions.DEFAULT);
  49. ret.put("msg",bulkResponse);
  50. return ret;
  51. }catch (IOException e){
  52. ret.put("msg",e.getStackTrace());
  53. e.printStackTrace();
  54. }
  55. return ret;
  56. }
  57. /**
  58. * 从es中删除一条数据
  59. */
  60. public Map<String,Object> deleteUser(String id){
  61. Map<String,Object> ret = new HashMap<>();
  62. BulkRequest request = new BulkRequest();
  63. request.add(new DeleteRequest(userIndex,userType,id));
  64. try {
  65. BulkResponse bulkResponse = client.bulk(request, RequestOptions.DEFAULT);
  66. ret.put("msg",bulkResponse);
  67. return ret;
  68. }catch (IOException e){
  69. ret.put("msg",e.getStackTrace());
  70. e.printStackTrace();
  71. }
  72. return ret;
  73. }
  74. /**
  75. * 条件查询
  76. */
  77. public List getUsers(Map<String,Object> maps) throws IOException {
  78. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  79. BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
  80. //判断是否是条件查询
  81. if (maps != null) {
  82. Set<String> keys = maps.keySet();
  83. for (String key: keys) {
  84. boolQueryBuilder.must(QueryBuilders.matchPhraseQuery(key, maps.get(key)));
  85. }
  86. } else {
  87. MatchAllQueryBuilder matchAllQueryBuilder = QueryBuilders.matchAllQuery();
  88. boolQueryBuilder.should(matchAllQueryBuilder);
  89. }
  90. searchSourceBuilder.query(boolQueryBuilder).size(10).from(0).sort("age", SortOrder.DESC);//分页以及排序
  91. SearchRequest searchRequest = new SearchRequest();
  92. searchRequest.indices(userIndex);
  93. searchRequest.types(userType);
  94. searchRequest.source(searchSourceBuilder);
  95. SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
  96. List list = new ArrayList();
  97. for (SearchHit hit: searchResponse.getHits()) {
  98. String s = JSON.toJSONString(hit);
  99. JSONObject o = JSON.parseObject(s);
  100. list.add(o.getJSONObject("sourceAsMap"));
  101. }
  102. return list;
  103. }
  104. }

后续会更新springboot+elasticsearch空间检索示例。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/68726
推荐阅读
相关标签
  

闽ICP备14008679号