一. 加入依赖
需要对应ES版本
<!--ElasticSearch 依赖-->
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.9.1</version>
</dependency>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>7.9.1</version>
</dependency>
<!--阿里 fastjson-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.58</version>
</dependency>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
二.配置 application.yml
es:
host: 127.0.0.1
port: 9200
protocol: http
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Configuration
public class EsEnvironmentProperties{
@Value("${es.host}")
private String host; // ES请求地址
@Value("${es.port}")
private int port; //端口
@Value("${es.protocol}")
private String protocol; //协议
// 可配置多ES
@Bean(name = "restHighLevelClientPre")
public RestHighLevelClient getRestHighLevelClientPre() {
return new RestHighLevelClient(RestClient
.builder(new HttpHost(host, port, protocol)));
}
}
三. 封装ES操作
@Component
public class ESUtils {
private static RestHighLevelClient restHighLevelClient;
private static volatile ESUtils eSUtils;
private ESUtils(){}
public static ESUtils getInstance(RestHighLevelClient restclient) {
restHighLevelClient = restclient;
if (eSUtils == null) {
synchronized (ESUtils.class) {
if (eSUtils == null) {
eSUtils = new ESUtils();
}
}
}
return eSUtils;
}
/**
* 查询
* @param index 索引
* @param searchSourceBuilder
*/
public SearchResponse searchBySearchSourceBuilde(String index,
SearchSourceBuilder searchSourceBuilder) throws IOException {
// 组装SearchRequest请求
SearchRequest searchRequest = new SearchRequest(index);
searchRequest.source(searchSourceBuilder);
// 同步获取SearchResponse结果
SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
return searchResponse;
}
/**
* 批量插入 批量修改删除原理相同,也可混合 只需在 bulkRequest.add 不同请求即可
* @param jsonStrList 待插入集合 注:每个String元素需为json字符串
* @param index 索引
* @return
*/
public BulkResponse bulkInsert(List<String> jsonStrList,String index) {
BulkRequest bulkRequest = new BulkRequest();
for (String jsonStr : jsonStrList) {
IndexRequest indexRequest = new IndexRequest(index);
indexRequest.source(jsonStr, XContentType.JSON);
bulkRequest.add(indexRequest); // 加入到批量请求bulk
}
BulkResponse bulkResponse = null;
try {
bulkResponse = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
} catch (IOException e) {
e.printStackTrace();
}
return bulkResponse;
}
}
具体使用
@Resource(name = "restHighLevelClientPre")
RestHighLevelClient restHighLevelClient;
//查询
public void search() {
// user_city 完全匹配 Beijing 且 (-6-1 <= user_time <= -6-2)
QueryBuilder queryBuilder = QueryBuilders.boolQuery()
.must(QueryBuilders.termQuery("user_city", "Beijing"))
.must(QueryBuilders.rangeQuery("user_time").gte("-6-1 00:00:00"))
.must(QueryBuilders.rangeQuery("user_time").lte("-6-2 00:00:00"));
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(queryBuilder);
// 按 user_time 升序排序
searchSourceBuilder.sort("user_time", SortOrder.ASC);
// 设置返回数量
searchSourceBuilder.size(1000);
SearchResponse searchResponse = null;
try {
searchResponse = ESUtils.getInstance(restHighLevelClient)
.searchBySearchSourceBuilde("users", searchSourceBuilder);
} catch (IOException e) {
e.printStackTrace();
}
SearchHit[] hitsArr = searchResponse.getHits().getHits();
List<User> userList = new ArrayList<>();
for (SearchHit searchHit : hitsArr) {
User user = new User();
JSONObject source = JSONObject.parseObject(searchHit.getSourceAsString());
user.setUser_id(source.getString("user_id"));
user.setUser_name(source.getString("user_name"));
userList.add(user);
}
}
//批量插入
public void bulkInsert(List<User> userList) {
List<String> jsonList = new ArrayList<>();
for (User user : userList) {
// User 转为 Json字符串
jsonList.add(JSONObject.toJSONString(user));
}
BulkResponse bulkResponse = ESUtils.getInstance(restHighLevelClient).bulkInsert(jsonList, "users");
}