Elasticsearch【付诸实践 02】Java HTTP Rest client for ElasticSearch Jest 客户端集成(配置+增删改查测试源码)【推荐使用】

1.简介

SpringBoot 项目初始化时就有 NoSQL 选项 Spring Data Elasticsearch(Access+Driver) 此时 pom 文件里引入的依赖是 spring-boot-starter-data-elasticsearch 它的版本受到 springboot 版本的限制,不能自由选择对应的 ES 版本。

在这里插入图片描述
还有另一个选择就是 Jest,以下是 官网 的介绍:

在这里插入图片描述
简单说就是:ES 有 Java API 但是没有 Http Rest interface,Jest 就是它的 HTTP Client。

2.依赖

<!-- https://mvnrepository.com/artifact/io.searchbox/jest -->
<dependency>
	<groupId>io.searchbox</groupId>
	<artifactId>jest</artifactId>
	<version>6.3.1</version>
</dependency>

3.配置

spring:
  elasticsearch:
    jest:
      uris: http://localhost:9200

4.使用

(1)创建客户端【官网代码】

// Construct a new Jest client according to configuration via factory
 JestClientFactory factory = new JestClientFactory();
 factory.setHttpClientConfig(new HttpClientConfig
                        .Builder("http://localhost:9200")
                        .multiThreaded(true)
			//Per default this implementation will create no more than 2 concurrent connections per given route
			.defaultMaxTotalConnectionPerRoute(<YOUR_DESIRED_LEVEL_OF_CONCURRENCY_PER_ROUTE>)
			// and no more 20 connections in total
			.maxTotalConnection(<YOUR_DESIRED_LEVEL_OF_CONCURRENCY_TOTAL>)
                        .build());
 JestClient client = factory.getObject();

(2)直接注入【配置文件进行参数配置】

    @Autowired
    JestClient jestClient;

5.测试源码

(1)创建索引

@SpringBootTest
class EsJestApplicationTests {
    @Autowired
    JestClient jestClient;
    @Test
    void createIndex() {
        // 创建对象
        User user = User.builder().id(1001).name("1号用户").age(22).build();
        // 创建索引
        Index index = new Index.Builder(user).index("user").type("name").build();
        // 执行创建方法
        try {
            jestClient.execute(index);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

创建成功:
在这里插入图片描述
(2)查询索引【注入等代码不再贴出 只贴出方法】

    @Test
    void queryIndex(){
        // 查询语句【可以在HiJson工具里编辑】
        String queryJson = "{\n" +
                "    \"query\": {\n" +
                "        \"match\": {\n" +
                "            \"name\": \"1号\"\n" +
                "        }\n" +
                "    }\n" +
                "}";
        // 创建查询
        Search search = new Search.Builder(queryJson).addIndex("user").addType("name").build();
        // 执行查询方法
        try {
            SearchResult result = jestClient.execute(search);
            System.out.println(result.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

输出结果【这里简单换个行 避免格式化后占较大篇幅】:

Result: 
{"took":47,"timed_out":false,
"_shards":{"total":5,"successful":5,"skipped":0,"failed":0},
"hits":{"total":1,"max_score":0.5753642,
"hits":[
{"_index":"user","_type":"name","_id":"1001","_score":0.5753642,
"_source":{"id":1001,"name":"1号用户","age":22}
}]}}, 
isSucceeded: true, 
response code: 200, 
error message: null

(3)更新索引【特别注意:更新语句官网给出的无法使用】

    @Test
    void updateIndex() {
        // 更新语句【可以在HiJson工具里编辑】
        String script = "{\n" +
                "    \"script\": {\n" +
                "        \"inline\": \"ctx._source.name += params.nameInfo\",\n" +
                "        \"params\": {\n" +
                "            \"new_nameInfo\": \"(懂事长)\"\n" +
                "        }\n" +
                "    }\n" +
                "}";
        // 创建更新
        Update update = new Update.Builder(script).index("user").type("name").id("1001").build();
        // 执行更新方法
        try {
            DocumentResult result = jestClient.execute(update);
            System.out.println(result.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

输出结果:

Result: {"_index":"user","_type":"name","_id":"1001","_version":3,"result":"updated",
"_shards":{"total":2,"successful":1,"failed":0},"_seq_no":2,"_primary_term":1}, 
isSucceeded: true, 
response code: 200, 
error message: null

页面查看:
在这里插入图片描述
(4)删除索引

    @Test
    void deleteIndex() {
        // 创建删除
        Delete delete = new Delete.Builder("1001").index("user").type("name").build();
        // 执行删除方法
        try {
            DocumentResult result = jestClient.execute(delete);
            System.out.println(result);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

输出结果:

Result: {"_index":"user","_type":"name","_id":"1001","_version":4,"result":"deleted",
"_shards":{"total":2,"successful":1,"failed":0},"_seq_no":3,"_primary_term":1}, 
isSucceeded: true, 
response code: 200, 
error message: null

6.总结

使用 Jest 的灵活性明显要比 Java api 要高,我们可以将增删改查的创建过程进行封装,输入参数获取解析后的结果。

  • 12
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值