Hey Scrilling,
Just FYI, I now created a very simple component class called ElasticAppSearchOperations
that mimics the ElasticsearchOperations
methods index()
and delete()
. There I am doing the Unirest calls and the mapping of my documents to a json that follows the Elastic App Search API conventions. For the mapping I am using the Jackson ObjectMapper that comes with the Spring Boot framework. The only thing I had to do is set the PropertyNamingStrategy
to snake case.
For anybody who is interested, this is the ElasticAppSearchOperations
(requires Spring Boot, Unirest and Lombok):
@Component
@Slf4j
public class ElasticAppSearchOperations {
@Value("${elasticappsearch.protocol}")
private String protocol;
@Value("${elasticappsearch.host}")
private String host;
@Value("${elasticappsearch.port}")
private int port;
@Value("${elasticappsearch.apikey}")
private String apikey;
@Autowired
ObjectMapper objectMapper;
public void delete(String id, String engineName) {
try {
var elasticAppSearchURL = new URL(protocol, host, port, "/api/as/v1/engines/" + engineName + "/documents");
var body = new JSONArray();
body.put(id);
Unirest.delete(elasticAppSearchURL.toString()).headers(getHeaders()).body(body).asJson().ifFailure(
jsonNodeHttpResponse -> log.error(
"Could not delete. Elastic App Search response status: {}, message: {}",
jsonNodeHttpResponse.getStatus(), jsonNodeHttpResponse.getBody()));
} catch (MalformedURLException e) {
log.error(e.getMessage(), e);
}
}
public void index(Object document, String engineName) {
try {
objectMapper.setPropertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE);
var elasticAppSearchURL = new URL(protocol, host, port, "/api/as/v1/engines/" + engineName + "/documents");
var body = new JSONArray();
body.put(new JSONObject(objectMapper.writeValueAsString(document)));
Unirest.post(elasticAppSearchURL.toString()).headers(getHeaders()).body(body).asJson().ifFailure(
jsonNodeHttpResponse -> log.error(
"Could not index. Elastic App Search response status: {}, message: {}",
jsonNodeHttpResponse.getStatus(), jsonNodeHttpResponse.getBody()));
} catch (MalformedURLException | JsonProcessingException e) {
log.error(e.getMessage(), e);
}
}
private Map<String, String> getHeaders() {
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
headers.put("Authorization", "Bearer " + apikey);
return headers;
}
}
Don't forget to add these lines to your application.properties
:
elasticappsearch.protocol=http
elasticappsearch.host=localhost
elasticappsearch.port=3002
elasticappsearch.apikey=
Then you can inject the component via @Autowire
and call the methods:
public class SomeClass {
@Autowired
ElasticAppSearchOperations elasticAppSearchOperations;
public void someMethod(Object yourModel) {
elasticAppSearchOperations.index(yourModel, "engine-name");
elasticAppSearchOperations.delete(yourModel.getId(), "engine-name");
}
This is not perfect, but does the job for me now.
Hope that helps!
Mirko