When I get results by query of Elasticsearch on Thymeleaf HTML, it shows as JSON, not as object like findAll
or findbyID
. I want to get as object then I can get values to table like user.firstname
, user.lastname
of elements
children of JSON like looking of index. How can I do this with GSON (JSON to object) or other way?
find all (index page) enter image description here
query search result: /searchresults/asd enter image description here
<tr th:each="food : ${query}">
<td th:text="${food.elements}">
<!--<td th:text="${food.id}"></td>
<td th:text="${food.firstName}"></td>
<td th:text="${food.lastName}"></td>
<td th:text="${movie.imglink}"></td>-->
Original JSON by my REST API: /search/query/test
{"timeTook":0.005,"numberOfResults":2,"elements":"[{\"highlight\":{\"lastName\":[\"<em>Asdfasd<\\/em>\"]},\"_index\":\"user\",\"_type\":\"_doc\",\"_source\":{\"firstName\":\"Test\",\"lastName\":\"Asdfasd\",\"modificationDate\":1595572482000,\"_class\":\"com.example.springmysqlelastic.model.UserModel\",\"id\":1},\"_id\":\"1\",\"sort\":[1],\"_score\":null},{\"highlight\":{\"lastName\":[\"<em>sadasd<\\/em>\"]},\"_index\":\"user\",\"_type\":\"_doc\",\"_source\":{\"firstName\":\"asfas\",\"lastName\":\"sadasd\",\"modificationDate\":1595572482000,\"_class\":\"com.example.springmysqlelastic.model.UserModel\",\"id\":2},\"_id\":\"2\",\"sort\":[2],\"_score\":null}]"}
Searchnormalcontroller.java
@Controller
public class SearchNormalController {
private final ISearchService searchService;
@Autowired
public SearchNormalController(ISearchService searchService) {
this.searchService = searchService;
}
@GetMapping("/searchresults/{query}") //value = {"/searchresults", "/"}
public String searchResultsFoods(@PathVariable String query, Model model) throws IOException {
model.addAttribute("query", searchService.searchFromQuery(query.trim().toLowerCase()));
return "searchresults";
}
}
searchservice.java
@Service
public class SearchService implements ISearchService {
//private ESConfig esco;
@Value("${api.elasticsearch.uri}")
private String elasticSearchUri;
@Value("${api.elasticsearch.search}")
private String elasticSearchSearchPrefix;
private static final Logger LOGGER = LoggerFactory.getLogger(SearchService.class);
@Override
public ResultQuery searchFromQuery(String query) throws IOException {
String body = HelperFunctions.buildMultiIndexMatchBody(query);
return executeHttpRequest(body);
}
/**
* Fetch resultQuery from elastic engine for the given body
*
* @param body String
* @return ResultQuery
* @throws IOException IOException
*/
private ResultQuery executeHttpRequest(String body) throws IOException{
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
ResultQuery resultQuery = new ResultQuery();
HttpPost httpPost = new HttpPost(HelperFunctions.buildSearchUri(elasticSearchUri
, "", elasticSearchSearchPrefix));
httpPost.setHeader(Constants.CONTENT_ACCEPT, Constants.APP_TYPE);
httpPost.setHeader(Constants.CONTENT_TYPE, Constants.APP_TYPE);
//esco.elasticsearchClient();
byte[] encodedBytes = Base64.encodeBase64("elastic:666666".getBytes());
String ELASTICUSER_PASS = new String(encodedBytes);
httpPost.setHeader("Authorization", "Basic " + ELASTICUSER_PASS);
//httpPost.setHeader("Authorization", "Basic ZWxhc3RpYzo2NjY2NjY=");
try {
httpPost.setEntity(new StringEntity(body, Constants.ENCODING_UTF8));
HttpResponse response = httpClient.execute(httpPost);
String message = EntityUtils.toString(response.getEntity());
JSONObject myObject = new JSONObject(message);
if(myObject.getJSONObject(Constants.HITS).getJSONObject("total")
.getInt("value") != 0){
resultQuery
.setElements(myObject
.getJSONObject(Constants.HITS)
.getJSONArray(Constants.HITS)
.toString());
resultQuery
.setNumberOfResults(myObject.getJSONObject(Constants.HITS).getJSONObject("total")
.getInt("value"));
resultQuery.setTimeTook((float) ((double) myObject.getInt(Constants.TOOK) / Constants.TO_MS));
} else {
resultQuery.setElements(null);
resultQuery.setNumberOfResults(0);
resultQuery.setTimeTook((float) ((double) myObject.getInt(Constants.TOOK) / Constants.TO_MS));
}
} catch (IOException | JSONException e) {
LOGGER.error("Error while connecting to elastic engine --> {}", e.getMessage());
resultQuery.setNumberOfResults(0);
}
return resultQuery;
}
}
}
resultquery.java
@NoArgsConstructor
@AllArgsConstructor
@Data
public class ResultQuery {
private Float timeTook; //ElasticSearch response time in seconds
private Integer numberOfResults; //the number of total elements retrieved
private String elements; //a stringified JSON that represents the total hits found.
}