当前位置:   article > 正文

java使用elasticsearchClient调用es7.17-生成连接、查询系统参数、索引相关操作_java 8 使用elasticsearchclient调用es

java 8 使用elasticsearchclient调用es

java调用elasticsearch有几种不同的方式,考虑到以后维护方便,使用elasticSearchClient进行数据交互

maven引入

首先要进行maven引入,后面两个是与json转化有关的,刚开始测试可以无需引入

	<dependency>
		<groupId>co.elastic.clients</groupId>
		<artifactId>elasticsearch-java</artifactId>
		<version>7.17.3</version>
	</dependency>
	<dependency>
		<groupId>com.fasterxml.jackson.core</groupId>
		<artifactId>jackson-databind</artifactId>
		<version>2.12.3</version>
	</dependency>
	<dependency>
		<groupId>jakarta.json</groupId>
		<artifactId>jakarta.json-api</artifactId>
		<version>2.0.1</version>
	</dependency>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

相关实体类

1、ModelTestCase

此实体整合了与es系统有关的相关参数

package com.media.business.esTest;

import co.elastic.clients.json.JsonpDeserializer;
import co.elastic.clients.json.JsonpMapper;
import co.elastic.clients.json.SimpleJsonpMapper;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.json.jsonb.JsonbJsonpMapper;
import jakarta.json.spi.JsonProvider;
import jakarta.json.stream.JsonGenerator;
import jakarta.json.stream.JsonParser;

import java.io.StringReader;
import java.io.StringWriter;
import java.lang.reflect.Method;
import java.util.Random;

import static org.junit.Assert.*;

public class ModelTestCase {
    // Same value for all tests in a test run
    private static final int RAND = new Random().nextInt(100);

    protected final JsonpMapper mapper;

    private JsonpMapper setupMapper(int rand) {
        // Randomly choose json-b or jackson
        switch(rand % 3) {
            case 0:
                System.out.println("Using a JsonB mapper (rand = " + rand + ").");
                return new JsonbJsonpMapper() {
                    @Override
                    public boolean ignoreUnknownFields() {
                        return false;
                    }
                };

            case 1:
                System.out.println("Using a Jackson mapper (rand = " + rand + ").");
                return new JacksonJsonpMapper() {
                    @Override
                    public boolean ignoreUnknownFields() {
                        return false;
                    }
                };

            default:
                System.out.println("Using a simple mapper (rand = " + rand + ").");
                return SimpleJsonpMapper.INSTANCE_REJECT_UNKNOWN_FIELDS;
        }
    }

    protected ModelTestCase() {
        this(RAND);
    }

    protected ModelTestCase(int rand) {
        mapper = setupMapper(rand);
    }

    protected <T> String toJson(T value) {
        return toJson(value, mapper);
    }

    public static <T> String toJson(T value, JsonpMapper mapper) {
        StringWriter sw = new StringWriter();
        JsonProvider provider = mapper.jsonProvider();
        JsonGenerator generator = provider.createGenerator(sw);
        mapper.serialize(value, generator);
        generator.close();
        return sw.toString();
    }

    public static <T> T fromJson(String json, Class<T> clazz, JsonpMapper mapper) {
        JsonParser parser = mapper.jsonProvider().createParser(new StringReader(json));
        return mapper.deserialize(parser, clazz);
    }

    protected <T> T fromJson(String json, Class<T> clazz) {
        return fromJson(json, clazz, mapper);
    }

    @SuppressWarnings("unchecked")
    protected <T> T checkJsonRoundtrip(T value, String expectedJson) {
        assertEquals(expectedJson, toJson(value));
        return fromJson(expectedJson, (Class<T>)value.getClass());
    }

    protected <T> T fromJson(String json, JsonpDeserializer<T> deserializer) {
        return fromJson(json, deserializer, mapper);
    }

    protected <T> T fromJson(String json, JsonpDeserializer<T> deserializer, JsonpMapper mapper) {
        JsonParser parser = mapper.jsonProvider().createParser(new StringReader(json));
        return deserializer.deserialize(parser, mapper);
    }


    public static void assertGetterType(Class<?> expected, Class<?> clazz, String name) {
        Method method;
        try {
            method = clazz.getMethod(name);
        } catch (NoSuchMethodException e) {
            fail("Getter '" + clazz.getName() + "." + name + "' doesn't exist");
            return;
        }

        assertSame(expected, method.getReturnType());
    }
}
  • 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

2、Person

此实体主要为测试索引中的数据结构

@Data
public class Person {
//    @JsonIgnore //这是doc_id,不用序列化
    private Integer id;
    
    private String name;
    private Integer age;

    @JsonFormat(pattern = "yyyy-MM-dd")
    private Date birthday;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

一、基础java调用

1、生成es连接

	//生成es连接
    private ElasticsearchClient getEsClient() {
        try {
            //调用es有同步和异步之分,下列方法是同步阻塞调用
            // Create the low-level client
            RestClient restClient = RestClient.builder(
                    new HttpHost(esIp, esPort)).build();

            // Create the transport with a Jackson mapper
            ElasticsearchTransport transport = new RestClientTransport(
                    restClient, new JacksonJsonpMapper());

            // And create the API client
            ElasticsearchClient client = new ElasticsearchClient(transport);

            return client;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("生成esClient失败" + e);
        }
        return null;
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

2、查询es相关信息

	//查询es系统相关信息
    @Test
    public void testCatRequest() throws IOException {
        ElasticsearchClient client = this.getEsClient();

        // Cat requests should have the "format=json" added by the transport
        NodesResponse nodes = client.cat().nodes(_0 -> _0);
        System.out.println(ModelTestCase.toJson(nodes, client._transport().jsonpMapper()));
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

二、索引相关

1、新建索引1

这种方式只是创建的一个空索引,如果需要对索引进行字段定义,用第二种方式

	public void addIndex() throws Exception {
        try {
            //判断索引是否存在
            boolean flag = ifExistIndex(indexName);
            if (flag) {
                System.out.println("索引已存在");
                return;
            }

            ElasticsearchClient client = this.getEsClient();

            CreateIndexResponse products = client.indices()
                    .create(c -> c.index(indexName)
                            //添加此索引的别名为foo
//                      .aliases("foo2", aliasBuilder -> aliasBuilder.isWriteIndex(true))
                    );
            System.out.println(JSON.toJSONString(products));
            System.out.println("成功");

            return;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("新增es索引失败" + e);
        }
        System.out.println("失败");
    }
  • 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

2、新建索引2

	@Test
    public void addIndex() throws Exception {
        try {
            ElasticsearchClient client = this.getEsClient();

            Person p = new Person(1,"张三",20,new Date());
            client.index(_1 -> _1
                    .index("testaaa")
                    .id(p.getId().toString())
                    .document(p));


            System.out.println(JSON.toJSONString(p));
            System.out.println("成功");

            return;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("新增es索引失败" + e);
        }
        System.out.println("失败");
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

3、判断索引是否存在

	//判断是否存在索引
    private boolean ifExistIndex(String indexName) throws Exception {
        ElasticsearchClient client = this.getEsClient();
        BooleanResponse existsResponse = client.indices().exists(b -> b.index(indexName));
        return existsResponse.value();
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Gausst松鼠会/article/detail/132657
推荐阅读
相关标签
  

闽ICP备14008679号