I have a requirement to implement a search engine. Like google / yahoo search, In a search component if any key entered it should find the matches and displayed. For this requirement i have created Spring Boot Project integrated with elastic search.
Using logstash i created index for my Oracle database in Elastic search., By using below code am able to fetch records based on Elastic Search Index id.
private final String INDEX = "bookdata";
private final String TYPE = "books";
public Map<String, Object> getBookById(String id){
GetRequest getRequest = new GetRequest(INDEX, TYPE, id);
GetResponse getResponse = null;
try {
getResponse = restHighLevelClient.get(getRequest);
} catch (java.io.IOException e){
e.getLocalizedMessage();
}
Map<String, Object> sourceAsMap = getResponse.getSourceAsMap();
return sourceAsMap;
}
The above code is working fine and am able to fetch Book based on ID. But i have to Author or Title of the book.
Please find my indexed documents in Elastic search from Kibana
{
"took": 34,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"skipped": 0,
"failed": 0
},
"hits": {
"total": 3,
"max_score": 1,
"hits": [
{
"_index": "bookdata",
"_type": "books",
"_id": "72c58f1a-7bfe-41be-a7f4-ee0aca3f4cf4", //able to search by ID
"_score": 1,
"_source": {
"id": "72c58f1a-7bfe-41be-a7f4-ee0aca3f4cf4",
"title": "Java Always", // want to search by Title
"author": "JournalDev", // or want to search by author
"price": 99.1
}
}
}
Am not very sure, how can in search with Author or Title of the book.
You need to use the search API instead of the Get API.
// create the search request
SearchRequest searchRequest = new SearchRequest(INDEX);
searchRequest.types(TYPE);
// create the match query on the author field
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
MatchQueryBuilder matchQueryBuilder = new MatchQueryBuilder("author", "JournalDev");
searchSourceBuilder.query(matchQueryBuilder);
searchRequest.source(searchSourceBuilder);
// send the request
SearchResponse searchResponse = restHighLevelClient.search(searchRequest);
// read the response
SearchHit[] searchHits = searchResponse.getHits().getHits();
for (SearchHit hit : searchHits) {
// get each hit as a Map
Map<String, Object> sourceAsMap = hit.getSourceAsMap();
String documentTitle = (String) sourceAsMap.get("title");
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With