java调用elasticsearch有几种不同的方式,考虑到以后维护方便,使用elasticSearchClient进行数据交互
首先要进行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>
此实体整合了与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());
}
}
此实体主要为测试索引中的数据结构
@Data
public class Person {
// @JsonIgnore //这是doc_id,不用序列化
private Integer id;
private String name;
private Integer age;
@JsonFormat(pattern = "yyyy-MM-dd")
private Date birthday;
}
//生成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;
}
//查询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()));
}
这种方式只是创建的一个空索引,如果需要对索引进行字段定义,用第二种方式
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("失败");
}
@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("失败");
}
//判断是否存在索引
private boolean ifExistIndex(String indexName) throws Exception {
ElasticsearchClient client = this.getEsClient();
BooleanResponse existsResponse = client.indices().exists(b -> b.index(indexName));
return existsResponse.value();
}