springboot查询elasticsearch数据

springboot查询es数据

项目结构

在这里插入图片描述

导入项目pom依赖

需要的依赖主要由lombok,fastjson,elasticsearch,以及es的高阶high.client

 <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
 </dependency>
 <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>7.12.0</version>
 </dependency>
 <dependency>
           <groupId>org.elasticsearch.client</groupId>
           <artifactId>elasticsearch-rest-high-level-client</artifactId>
           <version>7.12.0</version>
            <exclusions>
                <exclusion>
                    <artifactId>elasticsearch</artifactId>
                    <groupId>org.elasticsearch</groupId>
                </exclusion>
            </exclusions>
  </dependency>
   <dependency>
           <groupId>com.alibaba</groupId>
           <artifactId>fastjson</artifactId>
           <version>1.2.62</version>
   </dependency>

搭建项目

数据库

/*
 Navicat Premium Data Transfer

 Source Server         : localhost
 Source Server Type    : MySQL
 Source Server Version : 80011
 Source Host           : localhost:3306
 Source Schema         : test

 Target Server Type    : MySQL
 Target Server Version : 80011
 File Encoding         : 65001

 Date: 21/10/2018 05:52:0user5
*/

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user`  (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '自增ID',
  `username` varchar(16) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL COMMENT '用户名',
  `password` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL COMMENT '密码',
  `gmt_create` datetime(0) NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间',
  `gmt_modified` datetime(0) NULL DEFAULT CURRENT_TIMESTAMP(0) ON UPDATE CURRENT_TIMESTAMP(0) COMMENT '修改时间',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of user
-- ----------------------------
userINSERT INTO `user` VALUES (1, 'zhangsan', 'aaa', '2018-10-21 05:50:03', '2018-10-21 05:50:11');
INSERT INTO `user` VALUES (2, 'lisi', 'bbb', '2018-10-21 05:50:14', '2018-10-21 05:50:48');
INSERT INTO `user` VALUES (3, 'wangwu', 'ccc', '2018-10-21 05:50:15', '2018-10-21 05:50:50');
INSERT INTO `user` VALUES (4, 'zhaoliu', 'ddd', '2018-10-21 05:50:17', '2018-10-21 05:50:54');
INSERT INTO `user` VALUES (5, 'tianqi', 'eee', '2018-10-21 05:50:18', '2018-10-21 05:50:56');
INSERT INTO `user` VALUES (6, 'xiaoming', 'fff', '2018-10-21 05:50:19', '2018-10-21 05:51:07');
INSERT INTO `user` VALUES (7, 'erming', 'ggg', '2018-10-21 05:50:21', '2018-10-21 05:51:14');
INSERT INTO `user` VALUES (8, 'xiaogang', 'hhh', '2018-10-21 05:50:25', '2018-10-21 05:51:18');
INSERT INTO `user` VALUES (9, 'lili', 'kkk', '2018-10-21 05:50:28', '2018-10-21 05:51:23');
INSERT INTO `user` VALUES (10, 'nalan', 'lll', '2018-10-21 05:50:37', '2018-10-21 05:51:29');
INSERT INTO `user` VALUES (11, 'xiaoya', 'mmm', '2018-10-21 05:50:39', '2018-10-21 05:51:47');
INSERT INTO `user` VALUES (12, 'yaer', 'nnn', '2018-10-21 05:50:41', '2018-10-21 05:51:50');

SET FOREIGN_KEY_CHECKS = 1;
testinfomationuseruser

resouce

配置为es的端口以及ip地址

application.yml
elasticsearch:
  host: localhost
  port: 9200

在这里插入图片描述

可以看见两个ip以及端口是一致的

config

package com.example.es_log.config;

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

/**
 * es配置信息类
 */
@Configuration
public class ElasticSearchConfig {
   /**
    * ip
    */
    @Value("${elasticsearch.host}")
    private String host;
    /**
    * 端口
    */
    @Value("${elasticsearch.port}")
    private int port;

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

result

package com.example.es_log.util;

import lombok.Builder;
import lombok.Data;

/**
 *  封装结果信息
 */
@Data
@Builder
public class Result {
    private int code;
    private String msg;
    private Object data;
    private int total;

    public static Result success(Object data){
        return Result.builder().code(200).msg("ok").data(data).build();
    }
    public static Result success(int code, String msg,Object data){
    return Result.builder().code(200).msg(msg).data(data).build();
    }
    public static Result error(int code, String msg){
        return Result.builder().code(code).msg(msg).build();
    }
}

entity

package com.example.es_log.entity;

import lombok.Data;

/**
 * es数据实体(我这里和数据库一致)
 */
@Data
public class User {
    private String username;
    private String password;
    private String dev_mac;
}

controller

package com.example.es_log.controller;

import com.example.es_log.service.UserService;
import com.example.es_log.util.Result;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
@RequestMapping("user")
public class UserController {
    @Resource
    private UserService userService;

    @PostMapping( "index")
    public Result getIndexEsResult(String index, String keyWord, Integer page, Integer size) throws Exception {
        Result result = userService.indexEsResult(index, keyWord, page, size);
        return result;
    }
}

service

package com.example.es_log.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.es_log.entity.User;
import com.example.es_log.util.Result;
import com.github.pagehelper.PageInfo;
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.client.indices.GetIndexRequest;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

/**
 *  查询elk数据
 */
@Service
public class UserService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    public Result indexEsResult(String index, String keyWord, Integer page, Integer size) throws Exception {
        //判断索引是否为空
        if (index == null && index == "") {
            return Result.error(400, "索引不能为空!");
        }
        boolean authIndex = indexEsExist(index);
        System.out.println(authIndex);
        if (authIndex != true) {
            return Result.error(400, "索引不存在!!!");
        }
        //构建查询条件 使用通配符查询
        BoolQueryBuilder boolQueryBuilder=new BoolQueryBuilder();
        //查询所有
        // boolQueryBuilder.must(QueryBuilders.matchAllQuery());
        /**
         * 使用shouldId查询,相当于sql中的or,一个值匹配多个字段进行查询
         * 支持username,password,dev_mac查询
         */
        boolQueryBuilder.should(QueryBuilders.matchPhraseQuery("username",keyWord));
        boolQueryBuilder.should(QueryBuilders.matchPhraseQuery("password",keyWord));
        boolQueryBuilder.should(QueryBuilders.matchPhraseQuery("dev_mac",keyWord));
        SearchSourceBuilder builder = new SearchSourceBuilder();
        // 设置查询条数
        builder.from(page).size(size).query(boolQueryBuilder);
        PageInfo<User> pageInfo=indexSearch(index,builder,page,size, User.class);
        if (pageInfo ==null){
            return null;
        }
        return Result.success(pageInfo);
    }

    /**
     * 验证索引是否存在
     *
     * @param index
     * @return
     */
    private boolean indexEsExist(String index) {
        boolean indexExist = false;
        try {
            //设置索引
            GetIndexRequest indexRequest = new GetIndexRequest(index);
            indexRequest.local(false);
            indexRequest.humanReadable(true);
            // 往es查询索引
            indexExist = restHighLevelClient.indices().exists(indexRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
            System.err.println("索引不存在!!!");
        }
        return indexExist;
    }

    /**
     *  查询数据
     * @param indexName
     * @param searchSourceBuilder
     * @param pageNum
     * @param pageSize
     * @param s
     * @param <T>
     * @return
     * @throws Exception
     */
    private <T> PageInfo<T> indexSearch(String indexName, SearchSourceBuilder searchSourceBuilder, int pageNum, int pageSize, Class<T> s) throws Exception {
        SearchRequest searchRequest = new SearchRequest(indexName);
        searchRequest.source(searchSourceBuilder);
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        SearchHits hits = searchResponse.getHits();
        JSONArray jsonArray = new JSONArray();
        for (SearchHit hit : hits) {
            String sourceAsString = hit.getSourceAsString();
            JSONObject jsonObject = JSON.parseObject(sourceAsString);
            jsonArray.add(jsonObject);
        }
        System.out.println("返回总数为:" + hits.getTotalHits());
        int total = (int) hits.getTotalHits().value;

        // 封装分页
        List<T> list = jsonArray.toJavaList(s);
        list.forEach(i->{
            System.out.println(i);
        });
        PageInfo<T> page = new PageInfo<>();
        page.setList(list);
        page.setPageNum(pageNum);
        page.setPageSize(pageSize);
        page.setTotal(total);
        page.setPages(total == 0 ? 0 : (total % pageSize == 0 ? total / pageSize : (total / pageSize) + 1));
        page.setHasNextPage(page.getPageNum() < page.getPages());
        return page;
    }
}

查询结果

在这里插入图片描述
successful!

如果运行不了,可以下载我码云仓库代码

https://gitee.com/FetterXxZzz/elk.git
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值