但是以這種方式獲取到的ES數(shù)據(jù)需要解析好幾層,沒(méi)有用JPA或Java API來(lái)的直接
上代碼
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Repository;
import org.springframework.web.client.RestTemplate;
@Repository
public class AppDownloadDao {
@Value("${elasticsearch.api.url:}")
private String misESHost;
@Autowired
private RestTemplate restTemplate;
public ResponseEntity<String> getReleaseApp() {
// ES 查詢語(yǔ)句
String requestStr = "{" +
" \"query\" : {" +
" \"bool\": {" +
" \"must\": [" +
" { \"match\": { \"app\": \"hunter\"}}," +
" { \"match\": { \"state\": \"2\"}}," +
" { \"match\": { \"releaseFlag\": \"1\"}}" +
" ]" +
" }" +
" }," +
" \"sort\": [" +
" {\"vcode\": \"desc\"}" +
" ]" +
"}";
// post方式請(qǐng)求數(shù)據(jù)
return restTemplate.postForEntity(misESHost, getRequestBody(requestStr), String.class);
}
private synchronized <T> HttpEntity<T> getRequestBody(T requestStr) {
HttpHeaders headers = new HttpHeaders();
MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
headers.setContentType(type);
headers.add("Accept", MediaType.APPLICATION_JSON.toString());
return new HttpEntity<>(requestStr, headers);
}
}