版本
SpringBoot == 3.0
Elasticsearch == 8.12.1
依赖
我使用的
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
还可以用,但我没用的。1,2一起用会报下面第一个错
bash
<dependency>
<groupId>co.elastic.clients</groupId>
<artifactId>elasticsearch-java</artifactId>
<version>8.12.1</version>
</dependency>
注意:elasticsearch7.17版本之前使用的是,现在已经被弃用
bash
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.17.18</version>
</dependency>
资料
之前看的elasticsearch7.17之前如何做的:链接
elasticsearch7.17以上的代码示例:链接
官方文档:链接
一个介绍:链接
报错
错误1:Correct the classpath of your application so that it contains compatible versions of the classes org
我的解决方法就是只用第一个依赖
错误2:Error deserializing co.elastic.clients.elasticsearch.core.search.Hit: jakarta.json.JsonException: Ja
其他
贴一个,elasticsearch7.17之前的配置,但最好还是用最新的方法
java
@Data
@Configuration
@ConfigurationProperties(prefix = "es")
public class ESConfig {
private String esUrl;
private String esUsername;
private String esPassword;
@Bean
public RestHighLevelClient configRestHighLevelClient() throws Exception {
String[] esUrlArr = esUrl.split(",");
List<HttpHost> httpHosts = new ArrayList<>();
for(String es : esUrlArr){
String[] esUrlPort = es.split(":");
httpHosts.add(new HttpHost(esUrlPort[0], Integer.parseInt(esUrlPort[1]), "http"));
}
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials(esUsername, esPassword));
RestClientBuilder builder = RestClient.builder(httpHosts.toArray(new HttpHost[0]))
.setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
System.out.println("ES配置完成");
return new RestHighLevelClient(builder);
}
}
java
@org.junit.Test
public void getDocument() throws Exception {
try (RestHighLevelClient client = new ESConfig().configRestHighLevelClient()) {
// 指定要搜索的索引名称
String indexName = "cartoon_reply_info";
// 创建搜索请求对象
SearchRequest searchRequest = new SearchRequest(indexName);
// 创建搜索请求的查询条件
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.matchQuery("content", "世界"));
searchSourceBuilder.query(QueryBuilders.matchAllQuery()); // 匹配所有文档
searchSourceBuilder.size(10); // 设置返回结果的数量
searchSourceBuilder.sort("mediaId", SortOrder.DESC); // 根据字段排序
searchSourceBuilder.highlighter(new HighlightBuilder().field("世界")); // 设置高亮字段
searchSourceBuilder.size(10);
// 将查询条件添加到搜索请求中
searchRequest.source(searchSourceBuilder);
// 执行搜索请求
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
// 处理搜索结果
// 您可以从 searchResponse 中获取搜索结果并进行进一步的处理
// 示例中省略了处理过程
for (SearchHit hit : searchResponse.getHits().getHits()) {
System.out.println(hit.getSourceAsString()); // 输出文档内容
}
} catch (IOException e) {
e.printStackTrace();
}
}