jar导入
代码示例:
<!-- 阿里JSON解析器 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.78</version>
</dependency>
<!--ES-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
配置文件
配置示例:
#ES配置
#ES连接地址
spring.elasticsearch.uris=ip:9200
#ES账号
spring.elasticsearch.username=username
#ES密码
spring.elasticsearch.password=password
spring.elasticsearch.connection-timeout=30s
ES工具类编写
代码示例:
package com.xxx;【修改引用地址】
import com.alibaba.fastjson.JSON;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.support.WriteRequest;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.core.TimeValue;
import org.elasticsearch.rest.RestStatus;
import org.springframework.stereotype.Service;
import java.io.IOException;
/**
* ES工具包
*
* @author gxl
*/
@Service
public class EsUtils {
/**
* ES连接
*/
public final RestHighLevelClient esClient;
public EsUtils(RestHighLevelClient esClient) {
this.esClient = esClient;
}
/**
* 新增ES数据
*
* @param index 索引
* @param id id
* @param object 新增实例
* @return
*/
public boolean index(String index, String id, Object object) {
try {
//创建ES客户端
IndexRequest indexRequest = new IndexRequest(index)
.id(id)
.source(JSON.toJSONString(object), XContentType.JSON);
//使用IMMEDIATE刷新策略【请求向ElasticSearch提交了数据,立即进行数据刷新,然后再结束请求】
indexRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE);
//新增ES数据
IndexResponse response