elasticsearch java简单应用

(1)依赖

compile('org.elasticsearch.client:elasticsearch-rest-client:6.8.15')

(2)EsClient类

@Component
public class EsClient {

	public RestClient create() {
		HttpHost[] hosts= new HttpHost[] {new HttpHost("127.0.0.1", 9201, "http")};
        RestClientBuilder builder = RestClient.builder(hosts);
        builder = builder.setRequestConfigCallback(new RestClientBuilder.RequestConfigCallback() {

			@Override
			public Builder customizeRequestConfig(Builder requestConfigBuilder) {
				return requestConfigBuilder.setConnectTimeout(5000).setSocketTimeout(60000);
			}
			
        });
        Header[] defaultHeaders = new Header[] { new BasicHeader("Accept", "application/json"), new BasicHeader("Content-type", "application/json") };
        builder.setDefaultHeaders(defaultHeaders);
        RestClient restClient = builder.build();
        return restClient;
	}
	
}

(3)测试和运行结果

JSONObject queryJson = new JSONObject();
JSONObject match = new JSONObject();
JSONObject matchWrapper = new JSONObject();
matchWrapper.put("match_all", match);
queryJson.put("query", matchWrapper);
queryJson.put("from", 0);
queryJson.put("size", 2);
String body = queryJson.toString();
log.info("{}", body);
StringEntity entity = new StringEntity(body, ContentType.APPLICATION_JSON);
String query = "/test/_search";
log.info(query);
Request request = new Request("GET", query);
request.setEntity(entity);
RestClient restClient = esClient.create();
Response rsp = restClient.performRequest(request);
String result = EntityUtils.toString(rsp.getEntity());
log.info("{}", result);
2024-01-17 16:09:28 [restartedMain] INFO  cn.hwd.TestRunner - body:{"size":2,"query":{"match_all":{}},"from":0} 
2024-01-17 16:09:28 [restartedMain] INFO  cn.hwd.TestRunner - query:/test/_search 
2024-01-17 16:09:28 [I/O dispatcher 1] WARN  org.elasticsearch.client.RestClient - request [GET http://127.0.0.1:9201/test/_search] returned 1 warnings: [299 Elasticsearch-7.17.6-f65e9d338dc1d07b642e14a27f338990148ee5b6 "Elasticsearch built-in security features are not enabled. Without authentication, your cluster could be accessible to anyone. See https://www.elastic.co/guide/en/elasticsearch/reference/7.17/security-minimal-setup.html to enable security."] 
2024-01-17 16:09:28 [restartedMain] INFO  cn.hwd.TestRunner - result:{"took":3,"timed_out":false,"_shards":{"total":1,"successful":1,"skipped":0,"failed":0},"hits":{"total":{"value":2,"relation":"eq"},"max_score":1.0,"hits":[{"_index":"test231208","_type":"_doc","_id":"1","_score":1.0,"_source":{
	"name": "tom",
	"age": 2,
	"gmt_create": "20231208100612"
}},{"_index":"test231208","_type":"_doc","_id":"2","_score":1.0,"_source":{
	"name": "a jerry",
	"age": 4,
	"gmt_create": "20231208100612"
}}]}}

你可能感兴趣的:(Elasticsearch,elasticsearch)