LAPTOP-KB9HII50\70708 %!s(int64=2) %!d(string=hai) anos
pai
achega
65e873507a

+ 246 - 0
starter/elasticsearch-starter/src/main/java/com/yihu/jw/elasticsearch/EsApiApplicationTests.java

@ -0,0 +1,246 @@
//package com.yihu.jw.elasticsearch;
//
//import com.alibaba.fastjson.JSON;
//import com.wsl.pojo.User;
//import org.apache.http.auth.AuthScope;
//import org.apache.http.auth.UsernamePasswordCredentials;
//import org.apache.http.client.CredentialsProvider;
//import org.apache.http.client.config.RequestConfig;
//import org.apache.http.impl.client.BasicCredentialsProvider;
//import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
//import org.apache.lucene.util.QueryBuilder;
//import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
//import org.elasticsearch.action.bulk.BulkRequest;
//import org.elasticsearch.action.bulk.BulkResponse;
//import org.elasticsearch.action.delete.DeleteRequest;
//import org.elasticsearch.action.delete.DeleteResponse;
//import org.elasticsearch.action.get.GetRequest;
//import org.elasticsearch.action.get.GetResponse;
//import org.elasticsearch.action.index.IndexRequest;
//import org.elasticsearch.action.index.IndexResponse;
//import org.elasticsearch.action.search.SearchRequest;
//import org.elasticsearch.action.search.SearchRequestBuilder;
//import org.elasticsearch.action.search.SearchResponse;
//import org.elasticsearch.action.support.master.AcknowledgedResponse;
//import org.elasticsearch.action.update.UpdateAction;
//import org.elasticsearch.action.update.UpdateRequest;
//import org.elasticsearch.action.update.UpdateResponse;
//import org.elasticsearch.client.RequestOptions;
//import org.elasticsearch.client.RestClient;
//import org.elasticsearch.client.RestClientBuilder;
//import org.elasticsearch.client.RestHighLevelClient;
//import org.elasticsearch.client.indices.CreateIndexRequest;
//import org.elasticsearch.client.indices.CreateIndexResponse;
//import org.elasticsearch.client.indices.GetIndexRequest;
//import org.elasticsearch.client.ml.PostDataRequest;
//import org.elasticsearch.common.unit.TimeValue;
//import org.elasticsearch.common.xcontent.XContentType;
//import org.elasticsearch.index.query.QueryBuilders;
//import org.elasticsearch.index.query.TermQueryBuilder;
//import org.elasticsearch.search.builder.SearchSourceBuilder;
//import org.elasticsearch.search.fetch.subphase.FetchSourceContext;
//import org.junit.jupiter.api.Test;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.beans.factory.annotation.Qualifier;
//import org.springframework.boot.test.context.SpringBootTest;
//
//import java.io.IOException;
//import java.sql.*;
//import java.util.ArrayList;
//import java.util.concurrent.TimeUnit;
//
//
///**
// * es 7.6.x  高级客户端测试API
// */
//@SpringBootTest
//class EsApiApplicationTests {
//
//
//    @Autowired
//    @Qualifier("restHighLevelClient")
//    private  RestHighLevelClient client;
//
//
//
//
//    /****************************************索引操作start**********************************************/
//    // 创建索引 Request
//    @Test
//    void TestCreateIndex() throws IOException {
//        //创建索引请求
//        CreateIndexRequest request = new CreateIndexRequest("wu_index");
//        //执行请求
//        CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT);
//        System.out.println(createIndexResponse);
//    }
//
//
//    //判断索引是否存在
//    @Test
//    void TestExistIndex() throws IOException {
//        GetIndexRequest request = new GetIndexRequest("test");
//
//
//
//
//        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
//        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("elastic","elastic"));
//
//
//        boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
//        System.out.println(exists);
//    }
//
//
//    //删除索引
//    @Test
//    void TestDeleteIndex() throws IOException {
//        DeleteIndexRequest request = new DeleteIndexRequest("wu_index");
//        AcknowledgedResponse delete = client.indices().delete(request, RequestOptions.DEFAULT);
//        System.out.println(delete);
//    }
//    /****************************************索引操作end**********************************************/
//
//
//
//
//    /****************************************操作文档start*********************************************/
//    //添加文档
//    @Test
//    void testAddDocument() throws IOException {
//        //创建对象
//        User user = new User("wusl", 3);
//        //创建请求
//        IndexRequest request = new IndexRequest("wu_index");
//
//        //  put /wu_index/_doc/1
//        request.id("1");
//        request.timeout(TimeValue.timeValueSeconds(1));
//
//        //放入数据  Json
//
//        String jsonString = JSON.toJSONString(user);
//        request.source(jsonString, XContentType.JSON);
//
//        //客户端发送请求 获取响应结果
//        IndexResponse index = client.index(request, RequestOptions.DEFAULT);
//
//        System.out.println(index.getIndex());
//        System.out.println(index.toString());
//        System.out.println(index.status());
//    }
//
//    //获取文档  判断是否存在    get  /index/doc/1
//    @Test
//    void testIsExists() throws IOException {
//        GetRequest getRequest = new GetRequest("wu_index", 1+"");
//        //不获取返回的 _source 的上下文
//        getRequest.fetchSourceContext(new FetchSourceContext(false));
//        getRequest.storedFields("_none_");
//        boolean exists = client.exists(getRequest, RequestOptions.DEFAULT);
//        System.out.println(exists);
//    }
//
//    //获取文档
//    @Test
//    void testGetDocument() throws IOException {
//        GetRequest getRequest = new GetRequest("wu_index","1");
//        GetResponse documentFields = client.get(getRequest, RequestOptions.DEFAULT);
//        System.out.println(documentFields.getSourceAsString());
//        System.out.println(documentFields);
//    }
//
//
//
//
//
//    @Test
//    void testGetSqlDocument() throws IOException, SQLException {
//        /*Connection connection = DriverManager.getConnection("jdbc:es://http:localhost:9200");
//        Statement statement = connection.createStatement();
//        ResultSet resultSet = statement.executeQuery("select * from wu_index");
//        System.out.println(resultSet);*/
//
//        GetRequest getRequest = new GetRequest("select * from wu_index","_sql","1");
//        GetResponse documentFields = client.get(getRequest, RequestOptions.DEFAULT);
//        System.out.println(documentFields);
//    }
//
//
//    //更新文档
//    @Test
//    void testUpdateDocument() throws IOException {
//        UpdateRequest updateRequest = new UpdateRequest("wu_index","1");
//        updateRequest.timeout("1s");
//
//        User wuslOne = new User("wuslOne", 18);
//        String string = JSON.toJSONString(wuslOne);
//        updateRequest.doc(string,XContentType.JSON);
//        UpdateResponse update = client.update(updateRequest, RequestOptions.DEFAULT);
//
//        System.out.println(update);
//    }
//
//    //删除
//    @Test
//    void testDeleteRequest() throws IOException {
//        DeleteRequest deleteRequest = new DeleteRequest("wu_index","3");
//        deleteRequest.timeout("1s");
//        DeleteResponse delete = client.delete(deleteRequest, RequestOptions.DEFAULT);
//        System.out.println(delete.status());
//    }
//
//
//    //特殊的,批量插入数据
//    @Test
//    void testBulkRequest() throws IOException {
//        BulkRequest bulkRequest = new BulkRequest();
//        bulkRequest.timeout("10s");
//
//
//        ArrayList<User> usersList = new ArrayList<>();
//        usersList.add(new User("lb",11));
//        usersList.add(new User("jy",12));
//        usersList.add(new User("ab",10));
//        usersList.add(new User("sb",13));
//        usersList.add(new User("db",14));
//        usersList.add(new User("qb",15));
//        usersList.add(new User("sl",16));
//
//
//        for (int i = 0; i < usersList.size(); i++) {
//            bulkRequest.add(new IndexRequest("wu_index").id(""+(i+1)).source(JSON.toJSONString(usersList.get(i)),XContentType.JSON));
//        }
//
//        BulkResponse bulk = client.bulk(bulkRequest, RequestOptions.DEFAULT);
//        System.out.println(bulk.hasFailures()); //是否失败
//    }
//
//    //查询
//    @Test
//    void testSearch() throws IOException {
//        SearchRequest searchRequest = new SearchRequest("wu_index");
//
//        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
//
//
//        //精确匹配
//        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "lb");
//        //匹配所有
//        QueryBuilders.matchAllQuery();
//        searchSourceBuilder.query(termQueryBuilder);
//        searchSourceBuilder.size();
//        searchSourceBuilder.from();
//        searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
//
//        searchRequest.source(searchSourceBuilder);
//
//        SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
//        System.out.println(search);
//
//    }
//
//
//
//}

+ 54 - 0
starter/elasticsearch-starter/src/main/java/com/yihu/jw/elasticsearch/ResultSetUtil.java

@ -0,0 +1,54 @@
package com.yihu.jw.elasticsearch;
import com.alibaba.fastjson.JSONArray;
import org.springframework.stereotype.Component;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.*;
/**
 * Created by Bing on 2022/8/10.
 */
@Component
public class ResultSetUtil {
   public List<Map<String,Object>> resultToMapList(ResultSet resultSet) throws SQLException {
       List<Map<String,Object>> result = new ArrayList<>();
       ResultSetMetaData md = resultSet.getMetaData();
       int columnCount = md.getColumnCount();
       while (resultSet.next()){
           Map<String,Object> tmp = new HashMap<>();
           for (int i = 1; i <= columnCount; i++) {
               tmp.put(md.getColumnName(i), resultSet.getObject(i));
           }
           result.add(tmp);
       }
       return  result;
   }
    public JSONArray resultToJSONArray(ResultSet resultSet) throws SQLException {
        JSONArray result = new JSONArray();
        ResultSetMetaData md = resultSet.getMetaData();
        int columnCount = md.getColumnCount();
        while (resultSet.next()){
            Map<String,Object> tmp = new HashMap<>();
            for (int i = 1; i <= columnCount; i++) {
                tmp.put(md.getColumnName(i), resultSet.getObject(i));
            }
            result.add(tmp);
        }
        return  result;
    }
    public <T> List<T> resultToEntity(ResultSet resultSet, Class<T> target) throws SQLException {
        List<T> result = new ArrayList<>();
        JSONArray list = resultToJSONArray(resultSet);
        if (list.size()>0){
            result = JSONArray.parseArray(list.toJSONString(),target);
        }
        return result;
    }
}