springboot整合ElasticSearch7.X实现简单增删改查+多条件查询

这边主要是demo,具体业务根据自己得流程创建就ok
一.导入相应的依赖

  <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.1.6.RELEASE</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.elasticsearch.client/elasticsearch-rest-high-level-client -->
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>7.1.1</version>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>7.1.1</version>
        </dependency>


        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.58</version>
        </dependency>


        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.10</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.0.1</version>
        </dependency>


        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.9</version>
        </dependency>

工具方法:将对象转为map对象

  public static <T> Map<String, Object> beanToMap(T bean) {
        Map<String, Object> map = new HashMap<>();
        if (bean != null) {
            BeanMap beanMap = BeanMap.create(bean);
            for (Object key : beanMap.keySet()) {
                if(beanMap.get(key) != null)
                    map.put(key + "", beanMap.get(key));
            }
        }
        return map;
    }

ym配置

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/nba?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
    username: root
    password: 123456
    druid:
      initial-size: 5 #连接池初始化大小
      min-idle: 10 #最小空闲连接数
      max-active: 20 #最大连接数
      web-stat-filter:
        exclusions: "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*" #不统计这些请求数据
      stat-view-servlet: #访问监控网页的登录用户名和密码
        login-username: druid
        login-password: druid

server:
  port: 8080

#mybatis:
#  mapper-locations:
#    - classpath:dao/*.xml
#    - classpath*:com/**/mapper/*.xml

logging:
  level:
    root: info
    com.xdclass.search: debug

elasticsearch:
  host: 192.168.137.131
  port: 9200

配置类

@Configuration
@ConfigurationProperties(prefix = "elasticsearch")
public class EsConfig {
    private String host;
    private Integer port;

    @Bean(destroyMethod = "close")
    public RestHighLevelClient client() {
        return new RestHighLevelClient(RestClient.builder(
                new HttpHost(host, port, "http")
        ));
    }

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public Integer getPort() {
        return port;
    }

    public void setPort(Integer port) {
        this.port = port;
    }
}


二.增加数据

 @Resource
    private RestHighLevelClient client;

    @Resource
    private NBAPlayerDao nbaPlayerDao;

    private static final String NBA_INDEX = "nba_latest";

    private static final int START_OFFSET = 0;

    private static final  int MAX_COUNT = 1000;

    @Override
    public boolean addPlayer(NBAPlayer player, String id) throws IOException {
        IndexRequest request = new IndexRequest(NBA_INDEX).id(id).source(beanToMap(player));
        IndexResponse response = client.index(request, RequestOptions.DEFAULT);
        System.out.println(JSONObject.toJSON(response));
        return false;
    }

三.查询数据(根据id)

 @Override
    public Map<String,Object> getPlayer(String id) throws IOException {
        GetRequest getRequest = new GetRequest(NBA_INDEX,id);
        GetResponse response = client.get(getRequest,RequestOptions.DEFAULT);
        return response.getSource();
    }

四.更新数据

@Override
    public boolean updatePlayer(NBAPlayer player,String id) throws IOException {
        UpdateRequest request = new UpdateRequest(NBA_INDEX,id).doc(beanToMap(player));
        UpdateResponse response = client.update(request,RequestOptions.DEFAULT);
        System.out.println(JSONObject.toJSON(response));
        return true;
    }

五.删除数据

 @Override
    public boolean deletePlayer(String id) throws IOException {
        DeleteRequest request = new DeleteRequest(NBA_INDEX,id);
        client.delete(request,RequestOptions.DEFAULT);
        return true;
    }

六.删除所有数据

 @Override
    public boolean deleteAllPlayer() throws IOException {
        DeleteByQueryRequest request = new DeleteByQueryRequest(NBA_INDEX);
        BulkByScrollResponse response = client.deleteByQuery(request,RequestOptions.DEFAULT);
        return true;
    }

七.导入所有数据

 @Override
    public boolean importAll() throws IOException {
        List<NBAPlayer> list = nbaPlayerDao.selectAll();
        for(NBAPlayer player: list){
            addPlayer(player,String.valueOf(player.getId()));
        }
        return true;
    }

八.单条件匹配查询+分页

 @Override
    public List<NBAPlayer> searchMatch(String key,String value) throws IOException {
        SearchRequest searchRequest = new SearchRequest(NBA_INDEX);
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.matchQuery(key,value));
        searchSourceBuilder.from(START_OFFSET);
        searchSourceBuilder.size(MAX_COUNT);
        searchRequest.source(searchSourceBuilder);
        SearchResponse response = client.search(searchRequest,RequestOptions.DEFAULT);
        System.out.println(JSONObject.toJSON(response));

        SearchHit[] hits = response.getHits().getHits();
        List<NBAPlayer> playerList = new LinkedList<>();
        for(SearchHit hit: hits){
            NBAPlayer player = JSONObject.parseObject(hit.getSourceAsString(),NBAPlayer.class);
            playerList.add(player);
        }

        return playerList;
    }

九.词条查询

    @Override
    public List<NBAPlayer> searchTerm(String key,String value) throws IOException {
        SearchRequest searchRequest = new SearchRequest(NBA_INDEX);
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.termQuery(key,value));
        searchSourceBuilder.from(START_OFFSET);
        searchSourceBuilder.size(MAX_COUNT);
        searchRequest.source(searchSourceBuilder);
        SearchResponse response = client.search(searchRequest,RequestOptions.DEFAULT);
        System.out.println(JSONObject.toJSON(response));

        SearchHit[] hits = response.getHits().getHits();
        List<NBAPlayer> playerList = new LinkedList<>();
        for(SearchHit hit: hits){
            NBAPlayer player = JSONObject.parseObject(hit.getSourceAsString(),NBAPlayer.class);
            playerList.add(player);
        }

        return playerList;
    }

十.前缀查询

 @Override
    public List<NBAPlayer> searchMatchPrefix(String key,String value) throws IOException {
        SearchRequest searchRequest = new SearchRequest(NBA_INDEX);
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.prefixQuery(key,value));
        searchSourceBuilder.from(START_OFFSET);
        searchSourceBuilder.size(MAX_COUNT);
        searchRequest.source(searchSourceBuilder);
        SearchResponse response = client.search(searchRequest,RequestOptions.DEFAULT);
        System.out.println(JSONObject.toJSON(response));
        SearchHit[] hits = response.getHits().getHits();
        List<NBAPlayer> playerList = new LinkedList<>();
        for(SearchHit hit: hits){
            NBAPlayer player = JSONObject.parseObject(hit.getSourceAsString(),NBAPlayer.class);
            playerList.add(player);
        }

        return playerList;
    }

十一.多条件查询

 SearchRequest searchRequest = new SearchRequest();
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        QueryBuilder matchPhraseQueryBuilder = QueryBuilders.matchPhraseQuery("displayNameEn", "james");
        QueryBuilder matchPhraseQueryBuilder1 = QueryBuilders.matchPhraseQuery("displayName", "贾斯汀");
        searchSourceBuilder.query(QueryBuilders.boolQuery()
        .must(matchPhraseQueryBuilder)
        .must(matchPhraseQueryBuilder1));
        searchRequest.source(searchSourceBuilder);
        SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
        SearchHit[] hits = search.getHits().getHits();
        List<NBAPlayer> playerList = new LinkedList<>();
        for(SearchHit hit: hits){
            NBAPlayer player = JSONObject.parseObject(hit.getSourceAsString(),NBAPlayer.class);
            playerList.add(player);
            System.out.println("===========>"+player);
        }

你可能感兴趣的:(springboot整合ElasticSearch7.X实现简单增删改查+多条件查询)