"请教大家一个问题 本地下载了es,启动了,也插入了数据,springboot项目写了一个测试方法查数据在执行到最后一行数据的时候报CommectionClosedException:Connection is closed 代码如下: CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(""elastic"", ""hx6f=XCq0XcI+O9DqwUQ"")); RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost(""127.0.0.1"", 9200)).setHttpClientConfigCallback((HttpAsyncClientBuilder httpAsyncClientBuilder) -> httpAsyncClientBuilder.setDefaultCredentialsProvider(credentialsProvider))); // 1.准备Request GetRequest request2 = new GetRequest(""spu"", ""1""); // 2.发送请求,得到响应 我只引入了spring-boot-starter-data-elasticsearch依赖,另外,我的springboot版本是2.3.5RELEASE,elasticsearch版本是8.6.2。 GetResponse response = client.get(request2, RequestOptions.DEFAULT);"
"import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.elasticsearch.search.sort.SortOrder; import org.elasticsearch.search.builder.SearchSourceBuilder;
public class ElasticsearchExample {
public static void main(String[] args) throws Exception {
// 建立连接
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(
new HttpHost(""localhost"", 9200, ""http"")
)
);
// 查询数据
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
sourceBuilder.query(QueryBuilders.matchQuery(""name"", ""John""));
sourceBuilder.sort(""age"", SortOrder.DESC);
sourceBuilder.from(0);
sourceBuilder.size(10);
SearchRequest searchRequest = new SearchRequest(""my-index"");
searchRequest.source(sourceBuilder);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
SearchHits hits = searchResponse.getHits();
for (SearchHit hit : hits.getHits()) {
System.out.println(hit.getSourceAsString());
}
// 关闭连接
client.close();
}
} 这个试一下。 此回答整理自钉群“Elasticsearch技术社区2群”"
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。