寫在前面
之前寫了有關(guān)elasticsearch的搭建和使用springboot操作elasticsearch,這次主要簡單說下使用RestHighLevelClient工具包操作es。
搭建環(huán)境和選擇合適的版本
環(huán)境還是以springboot2.7.12為基礎(chǔ)搭建的,不過這不重要,因?yàn)檫@次想說的是RestHighLevelClient操作elasticsearch,RestHighLevelClient版本使用的是7.6.2,還需要引入elasticsearch客戶端maven配置,版本也是7.6.2.
主要maven配置:
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>7.6.2</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.6.2</version>
</dependency>
<dependency>
<groupId>com.alibaba.fastjson2</groupId>
<artifactId>fastjson2</artifactId>
<version>2.0.32</version>
</dependency>
具體代碼實(shí)現(xiàn)
1.首先是通過springboot實(shí)例化RestHighLevelClient對象
package com.es.demo.config;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories;
import java.util.ArrayList;
import java.util.List;
@Configuration
public class ElasticsearchConfig {
@Value("${spring.elasticsearch.uris}")
private String urls;
@Bean
public RestHighLevelClient geClient() {
RestHighLevelClient client = null;
String[] split = urls.split(":");
HttpHost httpHost = new HttpHost(split[0], Integer.parseInt(split[1]), "http");
client = new RestHighLevelClient(RestClient.builder(httpHost));
return client;
}
}
2.RestHighLevelClient的簡單例子,這里我就沒有抽出來公共方法,只是簡單的寫了一下如何使用。
首先是接口
public interface ProductHighService {
Boolean save(ProductInfo... productInfo);
Boolean delete(Integer id);
ProductInfo getById(Integer id);
List<ProductInfo> getAll();
List<ProductInfo> query(String keyword);
}
然后是實(shí)現(xiàn)
@Service
public class ProductHighServiceImpl implements ProductHighService {
@Autowired
private RestHighLevelClient restHighLevelClient;
@Override
public Boolean save(ProductInfo... productInfo) {
// IndexRequest request = new IndexRequest();
// for (ProductInfo info : productInfo) {
// request.index("product-info").id(String.valueOf(info.getId()));
// request.source(XContentType.JSON, info);
// try {
// IndexResponse response = restHighLevelClient.index(request, RequestOptions.DEFAULT);
// // 打印結(jié)果信息
// System.out.println("_index: " + response.getIndex());
// System.out.println("id: " + response.getId());
// System.out.println("_result: " + response.getResult());
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//循環(huán)插入/更新
// UpdateRequest updateRequest = new UpdateRequest();
// for (ProductInfo info : productInfo) {
// updateRequest.index("product-info").id(String.valueOf(info.getId()));
// updateRequest.doc(XContentType.JSON, info);
// try {
// UpdateResponse response = restHighLevelClient.update(updateRequest, RequestOptions.DEFAULT);
// // 打印結(jié)果信息
// System.out.println("_index: " + response.getIndex());
// System.out.println("id: " + response.getId());
// System.out.println("_result: " + response.getResult());
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//批量操作estHighLevelClient.bulk()可以包含新增,修改,刪除
BulkRequest request = new BulkRequest();
Arrays.stream(productInfo).forEach(info -> {
IndexRequest indexRequest = new IndexRequest();
indexRequest.index("product-info").id(String.valueOf(info.getId()));
try {
//通過ObjectMapper將對象轉(zhuǎn)成字符串再保存,如果不轉(zhuǎn)的話存入的格式不是正常的json格式數(shù)據(jù),不能轉(zhuǎn)成對象
ObjectMapper objectMapper = new ObjectMapper();
String productJson = objectMapper.writeValueAsString(info);
indexRequest.source(productJson, XContentType.JSON);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
request.add(indexRequest);
});
try {
BulkResponse response = restHighLevelClient.bulk(request, RequestOptions.DEFAULT);
System.out.println(response.status().getStatus());
} catch (IOException e) {
throw new RuntimeException(e);
}
return null;
}
@Override
public Boolean delete(Integer id) {
DeleteRequest deleteRequest = new DeleteRequest().index("product-info").id(String.valueOf(id));
try {
DeleteResponse response = restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);
// 打印結(jié)果信息
System.out.println("_index: " + response.getIndex());
System.out.println("_id: " + response.getId());
System.out.println("result: " + response.getResult());
} catch (IOException e) {
throw new RuntimeException(e);
}
return null;
}
@Override
public ProductInfo getById(Integer id) {
GetRequest getRequest = new GetRequest().index("product-info").id(String.valueOf(id));
try {
GetResponse response = restHighLevelClient.get(getRequest, RequestOptions.DEFAULT);
// 打印結(jié)果信息
System.out.println("_index: " + response.getIndex());
System.out.println("_type: " + response.getType());
System.out.println("_id: " + response.getId());
System.out.println("source: " + response.getSourceAsString());
if (StringUtils.hasLength(response.getSourceAsString())) {
return JSONObject.parseObject(response.getSourceAsString(), ProductInfo.class);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return null;
}
@Override
public List<ProductInfo> getAll() {
SearchRequest request = new SearchRequest();
request.indices("product-info");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.matchAllQuery());
//restHighLevelClient在執(zhí)行默認(rèn)查詢時返回條數(shù)都是10條,查詢所有的時候要設(shè)置上size
//lasticsearch exception [type=illegal_argument_exception, reason=Result window is too large, from + size must be less than or equal to: [10000] but was [1000000]
//size不能設(shè)置查過10000條,
searchSourceBuilder.size(1000);
request.source(searchSourceBuilder);
List<ProductInfo> result = new ArrayList<>();
try {
SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
response.getHits().forEach(e -> {
ProductInfo productInfo = JSONObject.parseObject(e.getSourceAsString(), ProductInfo.class);
result.add(productInfo);
});
} catch (IOException e) {
throw new RuntimeException(e);
}
return result;
}
@Override
public List<ProductInfo> query(String keyword) {
//https://blog.csdn.net/qq_38826019/article/details/121344376
SearchRequest request = new SearchRequest();
request.indices("product-info");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.matchQuery("productName", keyword));
searchSourceBuilder.query(QueryBuilders.matchQuery("description", keyword));
//分頁
// searchSourceBuilder.from();
// searchSourceBuilder.size()
request.source(searchSourceBuilder);
List<ProductInfo> result = new ArrayList<>();
try {
SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
response.getHits().forEach(e -> {
ProductInfo productInfo = JSONObject.parseObject(e.getSourceAsString(), ProductInfo.class);
result.add(productInfo);
});
} catch (IOException e) {
throw new RuntimeException(e);
}
return result;
}
}
這里注意一點(diǎn):restHighLevelClient在執(zhí)行查詢的時候默認(rèn)返回10條,所以如果查詢數(shù)量大于10條的話需要手動設(shè)置sizesearchSourceBuilder.size(1000),但是size的大小不能查過10000條,es有限制查詢記錄數(shù)不能超過10000,如果設(shè)置過大就會報(bào)錯:elasticsearch exception [type=illegal_argument_exception, reason=Result window is too large, from + size must be less than or equal to: [10000] but was [1000000]文章來源:http://www.zghlxwxcb.cn/news/detail-629037.html
最后
別的的話好像沒有遇到什么問題,因?yàn)槲揖褪菍懥艘粋€簡單的demo測試一下
demo地址:https://gitee.com/wdvc/es-demo.git,有興趣可以看下。文章來源地址http://www.zghlxwxcb.cn/news/detail-629037.html
到了這里,關(guān)于項(xiàng)目中使用es(二):使用RestHighLevelClient操作elasticsearch的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!