当前位置:   article > 正文

SpringBoot集成ElasticSearch7进行增删查改_springboot es 7 delete

springboot es 7 delete

SpringBoot集成ElasticSearch7进行增删查改

引入pom依赖

        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>7.6.0</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.6.0</version>
        </dependency>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

测试类

package com.elasticsearch.utils;

import com.alibaba.fastjson.JSON;
import com.configserver.uitis.StringUtils;
import com.elasticsearch.pojo.Lexer;
import org.apache.http.HttpHost;
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.SearchResponse;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.*;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.FetchSourceContext;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;

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


/**
 * Elasticserach RestClient示例
 * @author liudean
 *
 */
public class ESTest {


    // 初始化api客户端
    public static RestHighLevelClient client = new RestHighLevelClient(
            RestClient.builder(
                    new HttpHost("192.XXX.XX.XX",9200, "http")
            ));


    /**
     * 封装查询条件,可以直接调用
     * @throws Exception
     */
    public static BoolQueryBuilder queryBuilderData(String name,String text){
        BoolQueryBuilder boolBuilder = QueryBuilders.boolQuery();
        //filter 效率比 must高的多
//        if (StringUtils.isNull(aa)) {
//            queryBuilder.filter(QueryBuilders.termQuery("routerDatabaseNo", aa));
//        }
        if(!StringUtils.isNull(name)) {
            boolBuilder.must(QueryBuilders.matchPhraseQuery("createName", name));
        }
        if(!StringUtils.isNull(text)) {
            boolBuilder.must(QueryBuilders.matchPhraseQuery("text", text));
        }
        return boolBuilder;

    }
    public static void main(String[] args) throws Exception{
        //findUserName("liu","3");
        CreateDocument();
        //ExistIndex();
        //DeleteIndex();
        //IsExists();
        //getDocument();
        //updateDocument();
        //deleteDocument();
    }

    /**
     * 判断索引是否存在
     * @throws Exception
     */
    public static void ExistIndex()throws Exception{
        GetIndexRequest request = new GetIndexRequest("test");
        boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
        System.out.println(exists);
    }

    /**
     * 删除索引
     * @throws Exception
     */
    public static void DeleteIndex()throws Exception{
        DeleteIndexRequest request = new DeleteIndexRequest("test");
        AcknowledgedResponse delete = client.indices().delete(request, RequestOptions.DEFAULT);
        System.out.println(delete.isAcknowledged()); //为true表示删除成功
    }


    /**
     * 添加文档
     * @throws Exception
     */
    public static void CreateDocument()throws Exception{
        //Lexer是实体类  对应的就是es的字段名
        Lexer Bean = new Lexer();
        Bean.setCreateName("liu");
        Bean.setCreateDate(StringUtils.getDateSecond());
        Bean.setText("ceshi");
        Bean.setJsonData("json");
        Bean.setLoginfo("log");
        Bean.setProcedureInfo("pro");
        //test指的是你的索引名
        IndexRequest request = new IndexRequest("test");
        //设置规则 例如相当于 PUT /test/_doc/1 命令
        request.id("1").timeout(TimeValue.timeValueSeconds(1));//设置id,1秒超时
        request.timeout("1s");
        // 数据转换成json 放入请求
        request.source(JSON.toJSONString(Bean), XContentType.JSON);
        //将请求发出去,获取响应结果
        IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT);
        System.out.println(indexResponse.status()); // 返回当前操作的类型:CREATE
        System.out.println(indexResponse.toString()); //响应内容

    }

    /**
     * 判断文档是否存在
     * @throws Exception
     */
    public static void IsExists()throws Exception{
        GetRequest getRequest = new GetRequest("test", "1");
        // 不获取返回的_source 的上下文,会提高速度
        getRequest.fetchSourceContext(new FetchSourceContext(false));
        getRequest.storedFields("_none_");

        boolean exists = client.exists(getRequest, RequestOptions.DEFAULT);
        System.out.println(exists);
    }


    /**
     * 获取文档的信息 相当于GET /test/_doc/1
     * @throws Exception
     */
    public static void getDocument()throws Exception{
        GetRequest getRequest = new GetRequest("lexer", "1");

        GetResponse response = client.get(getRequest, RequestOptions.DEFAULT);

        System.out.println(response.getSourceAsString()); //获取文档的内容
    }

    /**
     * 根据条件获取文档
     * @throws Exception
     */
    public static void findUserName(String name,String text){
        RequestOptions.Builder options = RequestOptions.DEFAULT.toBuilder();
        //设置连接的库名 即_index 你的索引名是啥
        SearchRequest searchRequest = new SearchRequest("lexer");
        /// 搜索源构建对象
        SearchSourceBuilder search = new SearchSourceBuilder();
        //多条件查询
        BoolQueryBuilder boolBuilder=QueryBuilders.boolQuery();
		//区间查询
		//boolBuilder.must(QueryBuilders.rangeQuery("timestamp.keyword").gte(user.getStarttime()).lte(user.getEndtime()));
        //精确查询
        //boolBuilder.must(QueryBuilders.termQuery("fraction", user.getFraction));
        //模糊查询
        //boolBuilder.must(QueryBuilders.matchPhraseQuery("userName", user.getUsername()));
        //查询createName
        if(!StringUtils.isNull(name)) {
            boolBuilder.must(QueryBuilders.matchPhraseQuery("createName", name));
        }
        //根据text  wildcardQuery 这个是模糊查询 字符串+"*"
        //StringUtils.isNull  这个是我自己封装验证字符串为空的方法
        if(!StringUtils.isNull(text)) {
            boolBuilder.must(QueryBuilders.matchPhraseQuery("text", text));
        }
         String keyword = ".keyword";//使用 term 查询,然后通过 .keyword 取消分词就可做到完全匹配查询
        //根据text
        if(!StringUtils.isNull(text)) {
            boolBuilder.must(QueryBuilders.termQuery("text"+keyword, text));
        }
        //按照日期排序,如果不需要排序可以删掉
        search.sort("createDate.keyword", SortOrder.DESC);
        search.query(boolBuilder);
        searchRequest.source(search);
        SearchResponse response = null;
        try {
            //RequestOptions.DEFAULT
            response = client.search(searchRequest, options.build());
        } catch (IOException e) {

        }
        SearchHits hits = response.getHits();
        String totalNumber =String.valueOf(hits.getTotalHits());
        System.out.println(totalNumber);
        Map<String, Object> sourceAsMap= null;
        for (SearchHit hit :hits.getHits()) {
            sourceAsMap = hit.getSourceAsMap();
            System.out.println(sourceAsMap);
        }
    }


    /**
     * 更新文档信息
     * @throws Exception
     */
    public static void updateDocument()throws Exception{
        UpdateRequest request = new UpdateRequest("test", "1");
        request.timeout("1s");
        Lexer Bean = new Lexer();
        Bean.setCreateDate(String.valueOf(System.currentTimeMillis()));
        Bean.setText("setText");
        Bean.setJsonData("setJsonData");
        Bean.setLoginfo("setLoginfo");
        Bean.setProcedureInfo("setProcedureInfo");
        request.doc(JSON.toJSONString(Bean), XContentType.JSON);
        UpdateResponse response = client.update(request, RequestOptions.DEFAULT);
        System.out.println(response.status()); //成功返回 OK
        System.out.println(response.toString());
    }


    /**
     * 删除文档信息
     * @throws Exception
     */
    public static void deleteDocument()throws Exception{
        DeleteRequest request = new DeleteRequest("lexer", "1");

        request.timeout("1s");

        DeleteResponse response = client.delete(request, RequestOptions.DEFAULT);
        System.out.println(response.status()); //成功返回 OK
        System.out.println(response.toString());
    }

    /**
     * 批量操作
     * @throws Exception
     */
    public static void BulkRequest()throws Exception{
        BulkRequest request = new BulkRequest();
        request.timeout("10s");
        ArrayList<Object> list = new ArrayList<>();
        Lexer Bean1 = new Lexer();
        Lexer Bean2 = new Lexer();
        Lexer Bean3 = new Lexer();
        list.add(Bean1);
        list.add(Bean2);
        list.add(Bean3);

        //批量请求,批量更新,删除都差不多!!!不设置id就会自动生成随机id,演示为批量插入
        for (int i = 0; i < list.size(); i++) {
            request.add(new IndexRequest("test")
                    .id("" + (i + 1))
                    .source(JSON.toJSONString(list.get(i)), XContentType.JSON));
        }

        BulkResponse response = client.bulk(request, RequestOptions.DEFAULT);
        System.out.println(response.hasFailures());//是否失败,false表示成功,true表示失败
    }


    /**
     * 搜索查询+高亮
     * @throws Exception
     */
    public static void Query()throws Exception{
        SearchRequest request = new SearchRequest();
        //创建查询条件
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        // 使用QueryBuilders工具,精确查询term
        //QueryBuilders.matchAllQuery() 匹配所有
        TermQueryBuilder termQuery = QueryBuilders.termQuery("name", "hcode");

        //配置高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("name"); //绑定属性
        highlightBuilder.requireFieldMatch(false); //关闭多个高亮,只显示一个高亮
        highlightBuilder.preTags(" "); //设置前缀
        highlightBuilder.postTags(" "); //设置后缀
        sourceBuilder.highlighter(highlightBuilder);

        sourceBuilder.query(termQuery);
        sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));

        request.source(sourceBuilder);

        SearchResponse response = client.search(request, RequestOptions.DEFAULT);

        //获取结果对象
        SearchHits hits = response.getHits();

        System.out.println(JSON.toJSONString(hits));

        for (SearchHit searchHit : hits) {
            //获取高亮的html
            Map<String, HighlightField> highlightFields = searchHit.getHighlightFields();
            HighlightField name = highlightFields.get("name");

            //替换原有的字段
            Map<String, Object> sourceAsMap = searchHit.getSourceAsMap();

            if (name != null) {
                Text[] fragments = name.fragments();
                String light_name = "";
                for (Text fragment : fragments) {
                    light_name += fragment;
                }
                sourceAsMap.put("name", light_name); //进行替换
            }


            System.out.println(searchHit.getSourceAsMap());
        }
    }

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
  • 189
  • 190
  • 191
  • 192
  • 193
  • 194
  • 195
  • 196
  • 197
  • 198
  • 199
  • 200
  • 201
  • 202
  • 203
  • 204
  • 205
  • 206
  • 207
  • 208
  • 209
  • 210
  • 211
  • 212
  • 213
  • 214
  • 215
  • 216
  • 217
  • 218
  • 219
  • 220
  • 221
  • 222
  • 223
  • 224
  • 225
  • 226
  • 227
  • 228
  • 229
  • 230
  • 231
  • 232
  • 233
  • 234
  • 235
  • 236
  • 237
  • 238
  • 239
  • 240
  • 241
  • 242
  • 243
  • 244
  • 245
  • 246
  • 247
  • 248
  • 249
  • 250
  • 251
  • 252
  • 253
  • 254
  • 255
  • 256
  • 257
  • 258
  • 259
  • 260
  • 261
  • 262
  • 263
  • 264
  • 265
  • 266
  • 267
  • 268
  • 269
  • 270
  • 271
  • 272
  • 273
  • 274
  • 275
  • 276
  • 277
  • 278
  • 279
  • 280
  • 281
  • 282
  • 283
  • 284
  • 285
  • 286
  • 287
  • 288
  • 289
  • 290
  • 291
  • 292
  • 293
  • 294
  • 295
  • 296
  • 297
  • 298
  • 299
  • 300
  • 301
  • 302
  • 303
  • 304
  • 305
  • 306
  • 307
  • 308
  • 309
  • 310
  • 311
  • 312
  • 313
  • 314
  • 315
  • 316
  • 317
  • 318
  • 319
  • 320
  • 321
  • 322
  • 323
  • 324
  • 325
  • 326
  • 327
  • 328
  • 329
  • 330
  • 331

如果需要结合项目中,也可以这样写

package com.elasticsearch.config;

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

@Configuration
public class ElasticSearchClientConfig {
    // 初始化api客户端
    @Bean
    public RestHighLevelClient restHighLevelClient(){
        return new RestHighLevelClient(
                RestClient.builder(
                        //有几个集群写几个!!
                        new HttpHost("192.XXX.XX.XX",9200, "http"),
                        new HttpHost("192.XXX.XX.XX",9201, "http")
                )
        );
    }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

需要用的话直接注入就好了

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

闽ICP备14008679号