Elasticsearch: 权威指南 Java REST Client
可以跟着官网示例写demo
工欲善其事必先利其器,对于ES数据的查看,首先先安装一个谷歌浏览器的插件ElasticSearch Head,便于大家后期确认测试数据是否成功;
谷歌浏览器左上角存在一个“应用”标签,进入谷歌的应用商店;
搜索""安装成为扩展程序即可;然后打开,输入自己的ES服务地址,连接集群即可;
插件安装好之后,进入实践项目;
1、pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.15.0</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.75</version>
</dependency>
2、配置文件
server:
port: 8096
spring:
application:
name: elasticsearch
elasticsearch:
host: #{自定义服务器地址},例如127.0.0.1
port: 9200 端口
scheme: http
3、配置类
@Configuration
public class ElasticsearchConfig {
@Value("${elasticsearch.host}")
private String host;
@Value("${elasticsearch.port}")
private Integer port;
@Value("${elasticsearch.scheme}")
private String scheme;
/**
* 创建es客户端,设置主机服务器
*
* @return
*/
@Bean
public RestHighLevelClient restHighLevelClient() {
RestClientBuilder builder = RestClient.builder(
//单机部署
new HttpHost(host, port, scheme)
);
return new RestHighLevelClient(builder);
}
}
5、工具类
@Slf4j
public class ElasticsearchUtil {
@Autowired
private RestHighLevelClient restHighLevelClient;
//请求选项:设置授权等
public static final RequestOptions COMMON_OPTIONS;
static {
RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder();
//设置授权
//builder.addHeader("Authorization", "Bearer " + TOKEN);
//自定义消费响应
//builder.setHttpAsyncResponseConsumerFactory(
//new HttpAsyncResponseConsumerFactory
//.HeapBufferedResponseConsumerFactory(30 * 1024 * 1024 * 1024));
COMMON_OPTIONS = builder.build();
}
/**
* 创建索引
*
* @param elasticsearchIndex
* @throws IOException
*/
public void createIndex(ElasticsearchIndex elasticsearchIndex) throws IOException {
if (elasticsearchIndex == null) {
return;
}
IndexRequest indexRequest = new IndexRequest(elasticsearchIndex.getIndex());
indexRequest.id(elasticsearchIndex.getId());
//注意:json方式存入
indexRequest.source(elasticsearchIndex.getLogContent(), XContentType.JSON);
IndexResponse indexResponse = restHighLevelClient.index(indexRequest, COMMON_OPTIONS);
log.info("create es index success, response:{}", indexResponse);
}
/**
* 判断索引是否存在
*
* @param index
* @return
* @throws IOException
*/
public boolean existsIndex(String index) throws IOException {
GetRequest request = new GetRequest(index);
boolean exists = restHighLevelClient.exists(request, COMMON_OPTIONS);
log.info("existsIndex: " + exists);
return exists;
}
todo 后面关于索引、文档等各类工具类自定义补充,此处简单举例说明而已
}
6、ES实体
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class ElasticsearchIndex {
/**
* 索引名字
*/
private String index;
/**
* 索引类型
*/
private String type;
/**
* 文档记录id
*/
private String id;
/**
* 内容
*/
private String content;
}
封装一个实体对象,统一交互ES;
7、单测
注意:此处文档内容直接封装成JSON格式,故工具类创建索引时采用JSON类型,如果需要改动,可以自定义;
public class ElasticsearchTest {
@Autowired
private ElasticsearchUtil elasticSearchUtil;
@Test
public void test() throws IOException {
String content = "{\"name\":\"测试\"}";
ElasticsearchIndex index = ElasticsearchIndex.builder()
.index("test_index")
.id(UUID.randomUUID().toString().replace("-",""))
.logContent(content)
.build();
elasticSearchUtil.createIndex(index);
}
}
通过插件查看测试索引和文档是否创建成功
[testIndex] ElasticsearchStatusException[Elasticsearch exception [type=invalid_index_name_exception, reason=Invalid index name [testIndex], must be lowercase] 溪源更开始入门时,定义索引名字时,按照Java规范定义驼峰格式testIndex,发现报以上错误,报错信息也是提示我们索引名字必须以小写格式,故定义索引等其他字段时可以参考MySQL数据库字段格式要求,"_"下划线连接多个字段;