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

从零开始:SpringBoot整合ElasticSearch实现简单增删改查,第1张

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

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

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

Elasticsearch+Postman简单入门

Springboot集成ElasticSearch 1.引入相关依赖

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


    com.alibaba
    fastjson
    1.2.41



    org.elasticsearch.client
    elasticsearch-rest-high-level-client
    7.13.2
2.在application.properties文件中配置es连接

        可同时配置多个es连接

server.port=9650

spring.servlet.multipart.enabled=false
spring.servlet.multipart.file-size-threshold=0
spring.servlet.multipart.max-file-size=1MB
spring.servlet.multipart.max-request-size=10MB

elasticsearch.http.host=localhost
elasticsearch.http.port=9200
elasticsearch.user.index=user
elasticsearch.user.type=userInfo
3.编写配置类
package com.example.elasticsearchdemo.config;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ElasticsearchConfig {

    @Value("${elasticsearch.http.host}")
    private String esHost;
    @Value("${elasticsearch.http.port}")
    private int esPort;

    @Bean
    public RestHighLevelClient esRestClient() {
        RestClientBuilder builder = null;
        builder = RestClient.builder(new HttpHost(esHost,esPort,"http"));
        RestHighLevelClient restHighLevelClient = new RestHighLevelClient(builder);
        return restHighLevelClient;
    }

}
编写简单增删改查示例 1.用 postman 在es中设计并新建索引和映射

        具体方法可参考文章:

        Elasticsearch+Postman简单入门

        映射如下:

{
    "mappings": {
        "userInfo": {
            "properties": {
                "id": {
                    "type": "text",
                    "fields": {
                        "keyword": {
                            "type":"keyword",
                            "ignore_above":256
                        }
                    }
                },
                "name": {
                    "type": "text",
                    "fields": {
                        "keyword": {
                            "type":"keyword",
                            "ignore_above":256
                        }
                    }
                },
                "age": {
                    "type": "integer",
                    "fields": {
                        "keyword": {
                            "type":"keyword",
                            "ignore_above":256
                        }
                    }
                },
                "sex": {
                    "type": "text",
                    "fields": {
                        "keyword": {
                            "type":"keyword",
                            "ignore_above":256
                        }
                    }
                },
                "interest ": {
                    "type": "text",
                    "fielddata": true,
                    "fields": {
                        "keyword": {
                            "type":"keyword",
                            "ignore_above":256
                        }
                    }
                }
            }
        }
    }
}
2.在springboot中新建user类

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

ackage com.example.elasticsearchdemo.bean;

import org.springframework.data.annotation.Id;

public class User {

    @Id
    private String id;

    private String name;

    private Integer age;

    private String sex;

    private String interest;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getInterest() {
        return interest;
    }

    public void setInterest(String interest) {
        this.interest = interest;
    }

    @Override
    public String toString() {
        return "User{" +
                "id='" + id + ''' +
                ", name='" + name + ''' +
                ", age=" + age +
                ", sex='" + sex + ''' +
                ", interest='" + interest + ''' +
                '}';
    }
}
3.实现简单增删改查

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

1)Controller层
package com.example.elasticsearchdemo.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.elasticsearchdemo.bean.User;
import com.example.elasticsearchdemo.service.UserService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
@CrossOrigin(value = "*",  maxAge = 3600)

public class UserController {

    @Resource
    private UserService service;

    
    @RequestMapping(value = "save", method = RequestMethod.POST)
    public JSonObject saveUser(@RequestBody User user) {
        JSonObject output = new JSonObject();
        Map result = service.saveUser(user);
        output.put("msg", result);
        return output;
    }

    
    @RequestMapping(value = "delete/{id}", method = RequestMethod.DELETE)
    public JSonObject deleteUser(@PathVariable("id") String id) {
        JSonObject output = new JSonObject();
        Map result = service.deleteUser(id);
        output.put("msg", result);
        return output;
    }


    
    @RequestMapping(value = "get", method = RequestMethod.POST)
    public JSonObject getUsers(@RequestBody Map maps) throws Exception{
        JSonObject output = new JSonObject();
        List result = new ArrayList();
        if (maps != null) {
            result = service.getUsers(maps);
        } else {
            result = service.getAllUsers();
        }
        output.put("data", result);
        return output;
    }

}
2)Service层
package com.example.elasticsearchdemo.service;

import com.example.elasticsearchdemo.bean.User;
import com.example.elasticsearchdemo.dao.common.UserEsDao;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
public class UserService {

    @Resource
    private UserEsDao userEsDao;

    
    public Map saveUser(User user) {
        if (user.getId() == null) {
            //生成唯一随机id
            String id = UUID.randomUUID().toString().substring(24);
            user.setId(id);
        }
        return userEsDao.saveUser(user);
    }

    public Map deleteUser(String id) {
        return userEsDao.deleteUser(id);
    }

    public List getAllUsers() throws Exception{
        return userEsDao.getUsers(null);
    }

    public List getUsers(Map maps) throws Exception{
        return userEsDao.getUsers(maps);
    }

}
3)Dao层
package com.example.elasticsearchdemo.dao.common;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.elasticsearchdemo.bean.User;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;

import java.io.IOException;
import java.util.*;

@Repository
public class UserEsDao {

    @Autowired
    private RestHighLevelClient client;
    @Value("${elasticsearch.user.index}")
    private String userIndex;
    @Value("${elasticsearch.user.type}")
    private String userType;


    
    public Map saveUser(User user){
        Map ret = new HashMap<>();

        Map map = null;
        try{
            //实体转换成map以请求es
            map = JSON.parseObject(JSON.toJSonString(user), Map.class);
        }catch (Exception e){
            e.printStackTrace();
        }

        BulkRequest bulkRequest = new BulkRequest();
        //IndexRequest构造函数第三个参数指定id
        bulkRequest.add(new IndexRequest(userIndex,userType,user.getId()).source(map));
        try{
            BulkResponse bulkResponse = client.bulk(bulkRequest, RequestOptions.DEFAULT);
            ret.put("msg",bulkResponse);
            return ret;
        }catch (IOException e){
            ret.put("msg",e.getStackTrace());
            e.printStackTrace();
        }
        return ret;
    }

    
    public Map deleteUser(String id){
        Map ret = new HashMap<>();
        BulkRequest request = new BulkRequest();
        request.add(new DeleteRequest(userIndex,userType,id));
        try {
            BulkResponse bulkResponse = client.bulk(request, RequestOptions.DEFAULT);
            ret.put("msg",bulkResponse);
            return ret;
        }catch (IOException e){
            ret.put("msg",e.getStackTrace());
            e.printStackTrace();
        }
        return ret;

    }

    
    public List getUsers(Map maps) throws IOException {
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //判断是否是条件查询
        if (maps != null) {
            Set keys = maps.keySet();
            for (String key: keys) {
                boolQueryBuilder.must(QueryBuilders.matchPhraseQuery(key, maps.get(key)));
            }
        } else {
            MatchAllQueryBuilder matchAllQueryBuilder = QueryBuilders.matchAllQuery();
            boolQueryBuilder.should(matchAllQueryBuilder);
        }
        searchSourceBuilder.query(boolQueryBuilder).size(10).from(0).sort("age", SortOrder.DESC);//分页以及排序
        SearchRequest searchRequest = new SearchRequest();
        searchRequest.indices(userIndex);
        searchRequest.types(userType);
        searchRequest.source(searchSourceBuilder);
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
        List list = new ArrayList();
        for (SearchHit hit: searchResponse.getHits()) {
            String s = JSON.toJSonString(hit);
            JSonObject o = JSON.parseObject(s);
            list.add(o.getJSonObject("sourceAsMap"));
        }
        return list;
    }

}

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

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5636506.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存